How to compare "set" images in Imagebuttons?

Asked

Viewed 609 times

7

Personal how do I compare whether 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;

1 answer

8


You can use the method getConstantState() to check whether two Drawable are the same.

Bitmapdrawables created from the same Resource share the same bitmap stored in their 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 whether the Imagebutton has associated a particular Drawable:
Adapted from this reply

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 Imagebutton has not associated image check if 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();
}
  • It didn’t work, nothing happened

  • How so. I tested before posting. Edit your question and put the code there.

  • What is the android:targetSdkVersion app?

  • 15 the target and min in 4

  • Q1, Q2 and Q3 buttons have identical images?

  • Yes they are, and also they don’t fall in the first if

  • The images were attributed to Imagebutton through the attribute android:src=?

  • Assigns by setBackgroundResource

  • So replace getDrawable() for getBackground(). However I advise to use setImageResource() instead of setBackgroundResource().

  • Remember that a Imagebutton has by default a Backgroud attributed. That is why I believe that q1.getBackground() != null will always be true

  • Worked thanks!

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.