I am trying to do something in an if-statement, this works in every version of android (16 or higher because of the getDrawable) except Android L (tested on latest). The code is the following:
if (item.getIcon().getConstantState().equals(getResources().getDrawable(R.drawable.add_to_fav_normal).getConstantState())
Any help/hints or explanation would be appreciated!
Based on @alanv's answer, below is what I did and was successful:
Thank's @alanv :)
Use
item.getContext().getDrawable(int)
or the equivalentContextCompat
method.Starting in API 21, all framework widgets that load drawables use
Context.getDrawable()
which applies the context's current theme during inflation. This basically just callsgetResources().getDrawable(..., getTheme())
internally, so you could also usecontext.getResources().getDrawable(..., context.getTheme())
.In general, though, you shouldn't rely on this check. There are no API guarantees around what constant state you'll receive from a particular drawable.
This solution is convenient for tests only: