无论如何比较int到drawable?ANDROID

时间:2012-07-27 05:48:20

标签: java android object int

无论如何将s与a进行比较?在这段代码中我将int作为答案,如果drawable == s则我想显示"Correct!" toast消息。任何帮助将不胜感激。

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");
         }
    }
}

2 个答案:

答案 0 :(得分:2)

Drawable实例与int进行比较没有意义。你想做什么?您想检查方法res.getDrawable(R.drawable.exitbtn);是否返回正确的对象吗?

我认为从R文件中获取标识符是多余的:

int s = R.drawable.exitbtn;

然后使用相同的标识符获取对象:

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

然后尝试通过比较ID来检查它是否真的是正确的对象。

我认为在通过id获取Drawable时,没有错误的地方(特别是int值的混淆)。如果要确保已创建对象,请将其与空值进行核对。

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

另外,我认为没有办法从Drawable对象中获取id。 getDrawable返回的实例不包含此类信息。

更好的是,如果id在某种程度上是错误的,你可以使用getDrawable可以抛出NotFoundException的事实。查看docs了解详情。

答案 1 :(得分:1)

试试这个

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

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

或使用以下代码

  

使用getTag()和setTag()进行比较