Thomas
Thomas

Reputation: 467

Anyway to compare int to drawable?ANDROID

Is there anyway to compare s to a? In this code I have int s as the answer and if the drawable == s then I want to display a "Correct!" toast message. Any help would be appreciated.

btn1.setOnClickListener(new OnClickListener() 
{
    @Override
    public void onClick(View v) 
    {
          int s = R.drawable.exitbtn;
          Resources res = getResources();
          Drawable drawable = res.getDrawable(R.drawable.exitbtn);
          Object a=drawable;
          if(a==s)
          {
                ImageView imageview =(ImageView)findViewById(R.id.imageView1);
                Toast.makeText(getApplicationContext(), "CORRECT!", Toast.LENGTH_SHORT).show();
                imageview.setImageDrawable(drawable);
                btn1.setText("1");
                btn2.setText("2");
                btn3.setText("3");
                btn4.setText("4");
         }
    }
}

Upvotes: 1

Views: 4603

Answers (2)

Shyam
Shyam

Reputation: 6444

try this

public void MyClick(View view)
    {
     Drawable fDraw = view.getBackground();
     Drawable sDraw = getResources().getDrawable(R.drawable.twt_hover);

      if(fDraw.hashCode() == sDraw.hashCode())
      {
       //Not coming
      }
    }

or use following code

Use getTag() and setTag() for comparison

Upvotes: 1

toniedzwiedz
toniedzwiedz

Reputation: 18563

Comparing a Drawable instance to an int doesn't make sense. What are you trying to do? Do you want to check if the method res.getDrawable(R.drawable.exitbtn); returns the right object?

I think it's redundant to fetch an identifier from R-file:

int s = R.drawable.exitbtn;

Then fetch the object using the very same identifier:

Drawable drawable = res.getDrawable(R.drawable.exitbtn);

And then try to check whether it's really the right object by comparing ids.

I think that there's no place for mistake (specifically, confusion of an int value) when it comes to getting a Drawable by id. If you want to be sure the object has been created, check it against a null.

Drawable drawable = res.getDrawable(R.drawable.exitbtn);
if(drawable != null){
   //do stuff
} else {
   //handle the situation where there's no drawable
}

Also, I think there's no way to fetch an id from a Drawable object. The instance returned by getDrawable does not contain such information.

Better yet, you can use the fact that getDrawable can throw a NotFoundException if the id is somehow wrong. Check the docs for details.

Upvotes: 2

Related Questions