简体   繁体   中英

If Statement for Android TextView Message Display

How do I create an if statement for the Android setText() command?

For example, if I have something like:

Button button = (Button) findViewById(R.id.button);
TextView messageBox = (TextView)findViewById(R.id.message);
phrase[0] = "Hello World!";  //
phrase[1] = "Toast";         // array is declared earlier in code
Random r = new Random();
int  n = r.nextInt(1);
messageBox.setText(phrase[n]);

if(/*condition when phrase[1] is displayed in messageBox*/){
   // do stuff
}

The idea is that I want to structure an if statement that monitors when a certain message is displayed in my messageBox object.

Try this:

 Button button = (Button) findViewById(R.id.button);
    TextView messageBox = (TextView)findViewById(R.id.message);
    phrase[0] = "Hello World!";  //
    phrase[1] = "Toast";         // array is declared earlier in code
    Random r = new Random();
    int  n = r.nextInt(1);
    messageBox.setText(phrase[0]);

    if(messageBox.getText().toString().equals("Toast")){
       // do stuff
    }

Try this :

if(phrase[n].equals(messageBox.getText().toString())){

}

Do it like this:

Button button = (Button) findViewById(R.id.button);
TextView messageBox = (TextView) findViewById(R.id.message);
phrase[0] = "Hello World!";
phrase[1] = "Toast";
Random r = new Random();
int n = r.nextInt(1);
messageBox.setText(phrase[0]);

if(messageBox.getText().toString().equals("Toast")){
   //Write your code here when the result is Toast
} else {
   //Write your code here when the result is Hello World!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM