Reputation: 21
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.
Upvotes: 0
Views: 3068
Reputation: 6707
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!
}
Upvotes: 0
Reputation: 162
Try this :
if(phrase[n].equals(messageBox.getText().toString())){
}
Upvotes: 1
Reputation: 5261
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
}
Upvotes: 2