user2962142
user2962142

Reputation: 2066

How to compare 2 button backgrounds in Android?

So I have 2 buttons (or ImageButtons or even anything that can use a background) with the same background. I want a method to check whether they have the same background or not.

I tried 2 buttons with the same background, this

button1.getBackground();
button2.getBackground();

But they both returned different values.

Any other methods?

Upvotes: 0

Views: 1763

Answers (2)

Heshan Sandeepa
Heshan Sandeepa

Reputation: 3688

Try with tags, You can use tags in order to compare the background drawables .

    btn.setBackground(getResources().getDrawable(R.drawable.ic_launcher));
    btn.setTag(R.drawable.ic_launcher);

Then you can get the tag with ,

    btn.getTag();

and compare them.

Upvotes: 0

Ayan
Ayan

Reputation: 817

The getBackground() method returns a Drawable object.

Now to compare two Drawable objects its best to use the getConstantState() method to obtain them. This should work.

button1.getBackground().getConstantState().equals(button2.getBackground().getConstantState())

Upvotes: 1

Related Questions