0

Is it possible to stop getting negative numbers in TextView in android by writing a code in java.

I tried this

int up = 0;
TextView textview;

        if (allowNagativeNumbers == false) {
            if ( up < 0 ) 
            {
                up = 0;
                textview.setText(0);
            }
        }

but it still allows negative numbers. I am not sure if this code is right but by this code I mean everytime the value for up / text in textview is less then 0 e.g. -1 then change the value of up to 0 and make the textview text 0.

5
  • use a NumberSpinner instead Commented Dec 15, 2014 at 11:53
  • I have to use textview Commented Dec 15, 2014 at 11:54
  • Basically, in my app there is a button and if that button is pressed the textview will stop doing negative numbers but if that button is not pressed then it will do negative numbers along with positives. Commented Dec 15, 2014 at 11:55
  • Impossible to help you without a good code sample illustrating your problem. Commented Dec 15, 2014 at 11:57
  • Thanks for your help, I found the solution. Commented Dec 15, 2014 at 11:59

4 Answers 4

1

Before displaying your number in TextView use Math.abs() function on your number.This function will give you absolute value.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm guessing you want this to happen in real-time? Are you using a listener for the textview? If so make sure this is inside a listener and also double check and make sure that allowNegativeNumbers is actually false.

Comments

0

Implement your own TextView class (you will also be able to use it in XML files).

public class MyTextView extends TextView {

    @Override
    public void setText (CharSequence text, BufferType type)
    {
        if(Integer.valueOf(text) > 0)
        {
            super.setText (text, type);
        }
        else
        {
            super.setText ("0", type);
        }

}

Comments

0

Try These statements

int up = 5;
up = up >0 ? up: 0;

and set the text in textView.

another way

get the text from textView and convert it into string.

int up = Integet.parseInt(textView.getText());
up = up >0 ? up: 0;
and set the text in textView.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.