2011-05-04 45 views
0
 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.... 

這是我寫的代碼,沒有工作....檢查條件(繪製==繪製)

如果(((ImageView的)爲arg0).getDrawable()!= getResources( ).getDrawable(R.drawable.sq))

我已經使用了它,但沒有人清楚....他們說我們可以使用setTag()方法,但我無法弄清楚如何。所以請可憐我,告訴我如何使用setTag()來解決我的問題,例如

回答

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

     } 
    } 
} 

} 
+0

繪製與它沒有setTag()方法......,看起來像你不力ustand我的問題..或我dint ustand你的答案...所以PLZ給我一個小例子... wud是一個GR8的幫助 – vivek 2011-05-05 07:06:36

+0

我知道drawable沒有setTag()方法,我說的ImageView顯示drawable。對於每個ImageView,當您實例化它時,您可以設置它的標籤以輕鬆識別它顯示的繪圖。上面的代碼將變成: 'if((String)((ImageView)arg0).getTag()== DRAWABLE_SQ_TAG)' – Moystard 2011-05-05 08:28:15

+0

moystard,非常感謝您試圖回答...但我仍然努力讓你.. ..我得到的部分是:「當你實例化它時,你可以設置它的標籤來容易地識別它顯示的可繪製的」..怎麼?.try用一個例子來詳細說明它...... wud luv tht .. – vivek 2011-05-05 17:34:18