Android Studio中如何判断两个ImageButton是否使用完全相同的Drawable资源?
Your original code doesn't work because getDrawableState() returns an array of the view's current state flags (e.g., pressed, focused, enabled)—it has nothing to do with the actual background resource you're trying to compare. Using == on arrays checks for reference equality, not whether the background resources are identical.
Here's a reliable way to check if two ImageButtons share the same background Drawable resource:
public boolean areBackgroundsSame(ImageButton btn1, ImageButton btn2) { if (btn1 == null || btn2 == null) { return false; } Drawable bg1 = btn1.getBackground(); Drawable bg2 = btn2.getBackground(); // Both buttons have no background if (bg1 == null && bg2 == null) { return true; } // One has a background, the other doesn't if (bg1 == null || bg2 == null) { return false; } // Drawables from the same resource share the same constant state return bg1.getConstantState().equals(bg2.getConstantState()); }
How to use it:
ImageButton button1 = findViewById(R.id.btn1); ImageButton button2 = findViewById(R.id.btn2); if (areBackgroundsSame(button1, button2)) { // Run your code when backgrounds match }
Key Notes:
- This works for all Drawable types (bitmaps, vectors, state lists, etc.) as long as they're loaded from the same resource file.
- If you create Drawables dynamically (not from resources), this method won't work—you'll need to add custom identifiers (like setting a tag on the Drawable) to compare them.
内容的提问来源于stack exchange,提问作者LowFM
相关产品推荐
相关产品推荐

