1

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".

Alex
  • 615
  • 2
  • 7
  • 15

2 Answers2

1

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 ConstantStates 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.

Nathan Walters
  • 4,116
  • 4
  • 23
  • 37
  • Can you explain a little more what you mean when you say "track the state externally"? Now I know which is the error but not how to solve it. – Alex Oct 29 '14 at 08:44
  • Without much more context I can't give you a specific example, but basically you just want to maintain another variable that tracks, for example, if you've changed the background, it something like that. – Nathan Walters Oct 29 '14 at 11:11
1

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());
Alex
  • 615
  • 2
  • 7
  • 15
  • be careful using the getResources this is not compatible with api 21 and above. this is how it can be solved to ensure compatible for api 21 and below. http://stackoverflow.com/questions/27463737/compatibility-of-getcontext-and-getresource-between-5-0-and-lower – Phil3992 Dec 21 '14 at 15:22