How to check if the view is set the specific backg

2019-06-08 05:07发布

i am trying to compare the view background to the drawable but its not working for me.

View v1 = options.findViewById(i);
v1.findViewById(R.drawable.back);
Drawable d = v1.getBackground();       

if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back)){
    v1.setBackgroundResource(R.drawable.a);             
}else{
    view.setBackgroundResource(R.drawable.b);               
}

how to check i am getting an error here.

incompatible operand types Drawable.Constant State and Drawable

1条回答
太酷不给撩
2楼-- · 2019-06-08 06:08

1) Replace

if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back))

with

if(d.getConstantState() == getResources().getDrawable(R.drawable.correct_ans_back).getConstantState())

This will solve the incompatible operand types Drawable.Constant State and Drawable error.

2) If you are not able to compare two bitmaps, then you can use the below method.

public boolean compareDrawable(Drawable d1, Drawable d2){
    try{
        Bitmap bitmap1 = ((BitmapDrawable)d1).getBitmap();
        ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
        bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
        stream1.flush();
        byte[] bitmapdata1 = stream1.toByteArray();
        stream1.close();

        Bitmap bitmap2 = ((BitmapDrawable)d2).getBitmap();
        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, stream2);
        stream2.flush();
        byte[] bitmapdata2 = stream2.toByteArray();
        stream2.close();

        return bitmapdata1.equals(bitmapdata2);
    }
    catch (Exception e) {
        // TODO: handle exception
    }
    return false;
}

3) OR , you can assign two different TAG to the background images and compare the TAG only instead of comparing drawable directly. You can also set background's TAG as drawable's id and compare it as described below,

Object tag = bgView.getTag(); 
int backgroundId = R.drawable.bg_image;
if( tag != null && ((Integer)tag).intValue() == backgroundId) {
   //do your work.
}
查看更多
登录 后发表回答