2017-03-06 64 views
0

我嘗試訪問,我把在HashMap對象 這是我的相關代碼繪製資源:如何訪問繪製對在HashMap中

private void pairImagesCollection() { 
    mImages.put(R.drawable.img1, R.drawable.img1shadow); 
    mImages.put(R.drawable.img2, R.drawable.img2shadow); 
    mImages.put(R.drawable.img3, R.drawable.img3shadow); 
    mImages.put(R.drawable.img4, R.drawable.img4shadow); 
} 

private void checkMatch(View dragView, View view) { 
     ImageView target = (ImageView) view; 
     ImageView dragged = (ImageView) dragView; 
     Drawable image = dragged.getDrawable(); 
     int imgId = mImages.get(Integer.valueOf(image)); // wrong, I don't know how to do it ?! 
     target.setImageResource(imgId); 
    } 

任何幫助將評價!

+0

爲什麼你要通過'dra wable'對象到'valueOf()',它接受'String'將它轉換爲'int'? – Prashant

+0

@Prashant不,沒有字符串,我認爲R.drawable是獨一無二的,我可以通過imageview檢索所需的圖像 – yaffa

回答

0

INT imgId = mImages.get(Integer.valueOf(圖像));

不能通過Drawable得到ImageViewResource/Drawable Id。使用上面的代碼,您可以爲ImageView dragged設置標籤。之後,與您的mImages一起獲得價值。

checkMatch之前,您dragView設置標籤爲Drawble,這樣的事情:

dragged.setTag(R.drawable.img1); 

現在你可以getDrawableId

imgId = getDrawableId(dragged); 

    private int getDrawableId(ImageView iv) { 
     return (Integer) iv.getTag(); 
    } 
0

你有一個hashmap,存儲對圖像及其影子的引用嗎? 你想把哪個圖像放在圖像視圖上?你必須通過你的地圖迭代,把你想要的形象:否則你把pair.getValue

Iterator iterator = map.entrySet().iterator(); 
    while (iterator.hasNext()) { 
     Map.Entry pair = (Map.Entry)iterator.next(); 
     System.out.println(pair.getKey() + " = " + pair.getValue()); 
     } 

如果你想要把值圖像,然後你把pair.getKey()()

target.setImageResource(R.drawable.xxx); 
0

您可以使用Iterator

Iterator itObj = hashMapOBJ.entrySet().iterator(); 
         while (itObj .hasNext()) { 
          Map.Entry pair = (Map.Entry) itObj.next(); 

           String Key = (String) pair.getKey(); 
           Drawable Value = (Drawable) pair.getValue(); 
           hashMapOBJ.put(Key, Value); 
           System.out.println("Key: " + Key + "------>" + Value); 

         }