Constant states do not match in developer preview

2019-08-09 00:38发布

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!

3条回答
我命由我不由天
2楼-- · 2019-08-09 00:48

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 :)

查看更多
孤傲高冷的网名
3楼-- · 2019-08-09 00:57

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.

查看更多
女痞
4楼-- · 2019-08-09 01:07

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()));
}
查看更多
登录 后发表回答