How to compare "set" images in Imagebuttons?

6

How do I compare if the drawable image "set" in an ImageButton is equal to null for example, or the other Image contained in another Imagebutton?

   ImageButton q1 = (ImageButton) findViewById(R.id.q1);
    ImageButton q2 = (ImageButton) findViewById(R.id.q2);
    ImageButton q3 = (ImageButton) findViewById(R.id.q3);


    if (q1.getDrawable() != null &&
            q2.getDrawable() != null &&
            q3.getDrawable() != null) {

        Toast.makeText(this, "Teste 1", Toast.LENGTH_SHORT).show();

        if (q1.getDrawable().getConstantState().equals(q2.getDrawable().getConstantState()) &&
                q2.getDrawable().getConstantState().equals(q3.getDrawable().getConstantState())) {
            Toast.makeText(this, "Teste 2", Toast.LENGTH_SHORT).show();
            return true;
        }
    }

    return false;
    
asked by anonymous 02.05.2015 / 15:21

1 answer

7

You can use the getConstantState() method to check if two < in> Drawable are the same.

BitmapDrawables created from the same resource share the same bitmap stored in your ConstantState .

>
imgBt1 = (ImageButton)findViewById(R.id.imageButton1);
imgBt2 = (ImageButton)findViewById(R.id.imageButton2);

if(imgBt1.getDrawable().getConstantState().equals(imgBt2.getDrawable().getConstantState())){
    Toast.makeText(this, "Imagem igual", Toast.LENGTH_LONG).show();
}
else{
    Toast.makeText(this, "Imagem diferente", Toast.LENGTH_LONG).show();
}

To check if the ImageButton has associated a particular Drawable : Adapted from this

if(imgBt1.getDrawable().getConstantState().equals(
          getResources().getDrawable(R.drawable.ic_launcher).getConstantState())){
    Toast.makeText(this, "Imagem igual", Toast.LENGTH_LONG).show();
}
else{
    Toast.makeText(this, "Imagem diferente", Toast.LENGTH_LONG).show();
}

To check if the ImageButton does not have associated image, check that getDrawable() returns null

if(imgBt1.getDrawable() == null){
    Toast.makeText(this, "Botão não tem imagem", Toast.LENGTH_LONG).show();
}
else{
    Toast.makeText(this, "Botão tem imagem", Toast.LENGTH_LONG).show();
}
    
02.05.2015 / 16:52