Search code examples
androidandroid-5.0-lollipopandroid-resources

Comparing resources in API 21 x API 23


My app is running well in API 23 and above, but there seems to be a bug in it when I run it in API 21. I've narrowed it down to this piece of code:

if (myButton.getBackground().getConstantState() == ResourcesCompat.getDrawable(getResources(), R.drawable.myDrawable, null).getConstantState())
{...}

In API 21 it always returns false (even when it shouldn't), so I guess one of those methods doesn't work in API 21.

Any ideas? Is there any other way (compatible with API 21 and above) to check if a button's background has a specific drawable assigned to it?

ps: my minsdk is 21, but Lint is not giving me any warnings.


Solution

  • You can try using ContextCompat:

    ContextCompat.getDrawable(yourContext, R.drawable.myDrawable).getConstantState();