Reputation: 655
im coding the onClick method for a ImageButton and I have to compare the image in the button with another one from my resources folder to do some things. This is the code I wrote, where I put some log messages:
public void onClick(View v){
Log.e(LOGTAG, "bolarojo: "+getResources().getDrawable(R.drawable.bolarojo).getConstantState().toString());
Log.e(LOGTAG, "bolaclic: "+v.getBackground().getConstantState().toString());
if(v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.bolarojo).getConstantState())){
Log.e(LOGTAG, "buh");
And it shows: bolarojo: android.graphics.drawable.BitmapDrawable$BitmapState@4106ac08 bolaclic: android.graphics.drawable.StateListDrawable$StateListState@41070780 Since v is holding R.drawable.bolarojo shouldn't the log messages be the same? Anyways I don't undestand why it doesn't show "buh".
Upvotes: 1
Views: 3206
Reputation: 655
Well finally I solved it. I did a cast from the View to a ImageButton
ImageButton bla=(ImageButton)v;
And then I used the getDrawable() method and it works fine :D
bla.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.bolarojo).getConstantState());
Upvotes: 1
Reputation: 4136
If you look at the types of objects you're dealing with, you'll see that one of the objects has a constant state of type BitmapState
, while the other has StateListState
. Naturally, comparing two objects of different types will result in them not being equal. Even then, two ConstantState
s are not guaranteed to be equal, even if they come from the same drawable. Instead of comparing the backgrounds directly, track the state externally. That's likely to be much easier and more reliable.
Upvotes: 1