When taping on an ImageView, I want to replace it with other drawable depending on the previous drawable, with some researches I made this:
ImageView imgview = (ImageView) findViewById(R.id.imageView1);
imgview.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.imageView1 == imageView.getId());
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch (integer) {
case R.drawable.number1:
imageView.setImageResource(R.drawable.number2);
imageView.setTag(R.drawable.number2);
break;
case R.drawable.number2:
imageView.setImageResource(R.drawable.number3);
imageView.setTag(R.drawable.number3);
break;
case R.drawable.number3:
imageView.setImageResource(R.drawable.number4);
imageView.setTag(R.drawable.number4);
break;
default:
Toast.makeText(MainActivity.this, "exceeded", Toast.LENGTH_SHORT).show();
}
}
});
}
The problem is the app always calls to the toast message in default. It ingores all other treatments/verifications in case sections.
Any idea please to solve that problem?
Thank you very much.
The reason is
You have written following statement
So very first time control reached in click block that time tag will be null and above statement will make it 0.But you are doing nothing to handle case 0.
So in every case your tag will be 0 and it will cause default block execution.If you are setting tag as 0 then you must have switch case for 0.Otherwise it will always be 0 and default block keep on executing.
Your code snippet should look something like follow.