开发者

checking condition(drawable == drawable)

     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....

here's the code i wrote, which didn't work....

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

i have googled it but no one was clear....they were saying we could use setTag() method but i am not able to figure out How . so pl开发者_C百科ease have pity on me and tell me how could i use setTag() in solving my problem with a example


Using setTag() is pretty straightforward. Either you use void setTag (Object tag) and you just provide an object to identify your drawable (typically a String) or if you need to store several properties you can use the void setTag (int key, Object tag) to provide an integer key.

Code example (this code has not been tested but it should explain what I mean by itself):

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) {

        }
    }
}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜