【问题标题】:Anyway to compare int to drawable?ANDROID无论如何要将 int 与 drawable 进行比较?ANDROID
【发布时间】:2012-07-27 05:48:19
【问题描述】:

有没有可以将 s 与 a 进行比较?在这段代码中,我有 int s 作为答案,如果 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");
         }
    }
}

【问题讨论】:

  • 您想如何“比较”它们?画布的数字是多少?
  • 这就像将 NASA 火箭比作橙汁。

标签: java android object int


【解决方案1】:

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返回的实例不包含此类信息。

更好的是,您可以使用 getDrawable 可以在 id 出现某种错误时抛出 NotFoundException 的事实。详情请查看docs

【讨论】:

    【解决方案2】:

    试试这个

    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() 进行比较

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-05
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多