检查条件(drawable == drawable)

时间:2011-05-04 16:04:18

标签: android-widget

     sorry to ask question already asked. but i am helpless
   in my programi have 27 imageview's  which can display any of the 3 drawable's  i have in my drawable's folder.. and i want these imageview's  click to perform a different action for each drawable they contain..but i found that we won't be able to compare two drawable's for equality....

这是我写的代码,但是没有用....

if(((ImageView)arg0).getDrawable()!= getResources()。getDrawable(R.drawable.sq))

我用Google搜索了但没有人清楚......他们说我们可以使用setTag()方法,但我无法弄清楚如何。所以请怜悯我,告诉我怎么用setTag()来解决我的问题呢?

1 个答案:

答案 0 :(得分:0)

使用setTag()非常简单。要么使用void setTag(Object tag),只提供一个对象来标识drawable(通常是String),或者如果需要存储多个属性,可以使用void setTag(int key,Object tag)来提供整数键

代码示例(此代码尚未经过测试,但它应该解释我自己的意思):

class MyActivity extends Activity {

private static final String FIRST_IMAGE = "firstImage";
private static final String SECOND_IMAGE = "secondImage";

protected void onCreate (Bundle savedInstanceState) {
// Instantiation
ImageView imageView = (ImageView) findViewById(R.id.imgview);
imageView.setImageResource(R.drawable.firstimage);
imageView.setTag(FIRST_IMAGE); // The view is now tagged, we know this view embeds the first image
imageView.setOnClickListener(new ImageClickListener());

ImageView anotherImageView = (ImageView) findViewById(R.id.secondimgview);
anotherImageView.setImageResource(R.drawable.firstimage);
anotherImageView.setTag(FIRST_IMAGE); // The view is now tagged, we know this view embeds the first image
anotherImageView.setOnClickListener(new ImageClickListener());

ImageView secondImageView = (ImageView) findViewById(R.id.thirdimgview);
secondImageView.setImageResource(R.drawable.secondimage);
secondImageView.setTag(SECOND_IMAGE); // The view is now tagged, we know this view embeds the second image
secondImageView.setOnClickListener(new ImageClickListener());
}

private class ImageClickListener implements View.OnClickListener {

// The onClick method compares the view tag to the different possibilities and execute the corresponding action.
    public void onClick(View v) {
        String tag = (String) v.getTag();
        if (v.getTag() == FIRST_IMAGE) {
            // perform specific action
        } else if (v.getTag() == SECOND_IMAGE) {

        }
    }
}

}