javaandroidif-statementsettext

How do I use an if statement inside of setText?


I want to have a setText with an if statement inside, so I can easily pick a value for viewing. I remember seeing something like it in MIT App Inventor, so I think it's possible.

For example,

textView.setText(if (value == 0) {"no"}else {"yes"};

Solution

  • You can use the ternary operator.

    textView.setText(value == 0 ? "no" : "yes");
    

    Note that you can always just write out the if and else statements directly, though.

    if (value == 0) textView.setText("no");
    else textView.setText("yes");