Reputation: 3
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.
I cant randomize in my code, it closes always, but if I delete the call to the finish()
function, it will randomize normally.
I just want that imageview to recognize the image without a sqlite DB
@Override
public void onClick(View v) {
int[] cards={R.drawable.bg,R.drawable.bg1};
Random r = new Random();
int n = r.nextInt(2);
ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(cards[n]);
if (imgview1.equals(R.drawable.bg){
imgview1.setImageResource(cards[n]);
}
else {
finish();
}
}
Upvotes: 0
Views: 87
Reputation: 180
here 1)if condition misses One bracket. (imgview1.equals(R.drawable.bg))
2) Compare Image With int Because R.drawble.bg gives You Resource ID that not match..thats why its always goes to else
Solution:
ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(id);
imgview1.setTag(id);
if (imgview1.getTag() == R.drawable.bg) {
imgview1.setImageResource(id);
} else {
finish();
}
Upvotes: 0
Reputation: 37594
You if-condition
is always false because you are comparing an Object
to an int
which will never be true.
Unfortunately there is no ImageView#getDrawableId
so you have to use a work around with Imageview#setTag
e.g.
@Override
public void onClick(View v) {
int[] cards = {
R.drawable.bg,
R.drawable.bg1
};
int id = cards[new Random().nextInt(2)];
ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(id);
imgview1.setTag(id);
if (imgview1.getTag() == R.drawable.bg) {
imgview1.setImageResource(id);
} else {
finish();
}
}
Upvotes: 0
Reputation: 4051
Your Activity
always closes because you compare ImageView
and Resource
, it always false. To provide logic which you want, you can use setTag()
method, to set tag as image resource and then compare them:
ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(cards[n]);
imgview1.setTag(cards[n]);
if (imgview1.getTag().equals(R.drawable.bg) {
imgview1.setImageResource(cards[n]);
} else {
finish();
}
Upvotes: 1
Reputation: 341
Change this condition if (imgview1.equals(R.drawable.bg)
to
if (cards[n ] == R.drawable.bg)
Your problem is that you are comparing the ImageView reference to the ImageResource
Upvotes: 0