I was new in Android and found some good tutorials on the internet, so I tried a simple activity with an if-else
statement. I'm trying "correct and wrong" prompt/Toast
:
Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
I'm not sure what is wrong in my if-else
statement but never prompts at all. I tried removing the (iv1.equals(R.drawable.airplane3))
and (iv1.equals(R.drawable.airplane2))
then it only shows the wrong Toast. I can't get seem to make the correct to prompt me.
Here is the full code of my class:
public class MainActivity extends Activity {
private static final Random imagerandom = new Random();
private static final Integer[] Imagesnumber =
{ R.drawable.airplane1, R.drawable.airplane2, R.drawable.airplane3, };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Integer a = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
View nextButton = findViewById(R.id.button1);
nextButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View V) {
int resource = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
iv.setImageResource(resource);
}
});
Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}