Constant states do not match in developer preview android L

妖精的绣舞 提交于 2020-01-05 05:26:14

问题


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!


回答1:


Use item.getContext().getDrawable(int) or the equivalent ContextCompat 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 calls getResources().getDrawable(..., getTheme()) internally, so you could also use context.getResources().getDrawable(..., context.getTheme()).

     if (item.getIcon().getConstantState().equals(item.getContext()
                .getDrawable(R.drawable.add_to_fav_normal).getConstantState())

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.




回答2:


This solution is convenient for tests only:

public static void assertEqualDrawables(Drawable drawableA, Drawable drawableB) {
    Bitmap bitmap1 = ((BitmapDrawable) drawableA).getBitmap();
    Bitmap bitmap2 = ((BitmapDrawable) drawableB).getBitmap();
    ByteBuffer buffer1 = ByteBuffer.allocate(bitmap1.getHeight() * bitmap1.getRowBytes());
    bitmap1.copyPixelsToBuffer(buffer1);

    ByteBuffer buffer2 = ByteBuffer.allocate(bitmap2.getHeight() * bitmap2.getRowBytes());
    bitmap2.copyPixelsToBuffer(buffer2);

    Assert.assertTrue(Arrays.equals(buffer1.array(), buffer2.array()));
}



回答3:


Based on @alanv's answer, below is what I did and was successful:

if (imgClicked.getDrawable().getConstantState()
                    .equals(ContextCompat.getDrawable(this,
                            R.drawable.add_profile).getConstantState())) {

     //Both images are same

}else{

    //Both images are NOT same      

}

Thank's @alanv :)



来源:https://stackoverflow.com/questions/26756613/constant-states-do-not-match-in-developer-preview-android-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!