Compare Background with Drawable

1

I have a problem comparing Background of a ImageButton with a drawable

IB6 is my ImageButton and wanted to see if it has drawable def , when it arrives at this if the application for and gives error in equals

if (IB6.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.def).getConstantState()))

The program goes below because I'm comparing the Background of ImageButton to drawable badly.

How do I if check whether Background IB6 is equal to drawable def ??

    
asked by anonymous 30.01.2017 / 15:11

2 answers

4

getDrawable() does not return the background but the image assigned by android:src .

Instead of getDrawable() use getBackground()

if (IB6.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.def).getConstantState()))
    
30.01.2017 / 15:50
0

Try to transform drawable to Bitmap and compare using the sameAs .

Here's an example:

       final ImageButton buttonImage = ImageButton.class.cast(findViewById(R.id.facebookLogin));

        if(null != buttonImage.getDrawable()){
            final Drawable drawable = getResources().getDrawable(R.drawable.ic_facebook, null);



            if(  getBitmap(buttonImage.getDrawable()).sameAs(getBitmap(drawable)) ){

                Toast.makeText(getApplicationContext(), "São iguais", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), "Não são iguais", Toast.LENGTH_SHORT).show();

            }

}

method to transform into Bitmap:

public static Bitmap getBitmap(Drawable drawable) {
    Bitmap result;
    if (drawable instanceof BitmapDrawable) {
        result = ((BitmapDrawable) drawable).getBitmap();
    } else {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        // Some drawables have no intrinsic width - e.g. solid colours.
        if (width <= 0) {
            width = 1;
        }
        if (height <= 0) {
            height = 1;
        }

        result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
    }
    return result;
}
    
30.01.2017 / 15:34