Search code examples
javaandroidif-statementtextviewsettext

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.


Solution

  • 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
        }