2014-11-21 64 views
-1

我環顧四周,但沒有在任何地方找到我的問題的答案。我有一個imageButton,並希望在按下按鈕時更改圖像。我試圖找出一種方法讓Eclipse從字面上解釋我的代碼。在ImageButton上動態設置圖像

String card = nextcard.toString(); //Becomes "Ace_Of_Hearts", for example 
theImageButton.setImageResource(R.drawable.card); //R.drawable.Ace_Of_Hearts is an image in the correct folder 

不幸的是,這是行不通的。但是,因爲卡片變量動態變化,我不能硬編碼特定的圖像來設置按鈕。那麼我應該如何設置圖像?

+0

更好地闡述更多細節... – 2014-11-21 05:42:28

+1

裏面'if-else'條件改變圖像 – kId 2014-11-21 05:46:21

+0

我有一個ImageButton,我想知道的是如何設置圖像到該圖像按鈕。這個網站上的其他答案是不夠的,因爲他們推薦了一些與「setImageResource(R.drawable.YOUR_IMAGE)」一致的東西,如果你不是硬編碼,這是行不通的。 – 2014-11-21 05:47:05

回答

0

獲取在繪製目錄的所有卡的ID:

Integer ace_of_hearts_id = R.drawable.ace_of_hearts; 
Integer ace_of_spades_id = R.drawable.ace_of_spades; 
Integer queen_of_hearts_id = R.drawable.queen_of_hearts; 
Integer ten_of_hearts_id = R.drawable.ten_of_hearts; 
.... 

把ID和字符串名稱中的一個HashMap的鍵值對:

HashMap cardMap = new HashMap<String,Integer>(); 
    cardMap.put("ace_of_hearts",ace_of_hearts_id); 
    cardMap.put("ace_of_spades" ace_of_spades_id);  
...... 

然後加入您的代碼:

String card = nextcard.toString(); //Becomes "Ace_Of_Hearts", for example 
theImageButton.setImageResource(cardMap.get(card));/

Havent actua編譯代碼,所以可能有錯誤,但這應該給你一個基本的想法。

0

您可以使用imagebutton選擇器來做到這一點。 首先創建資源選擇/繪製btn_selector.xml

<?xml version="1.0" encoding="utf-8"?> 

<item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item> 
<item android:drawable="@drawable/button_bg_normal"></item> 

現在你可以使用這個selctor爲您的圖像按鈕的SRC。

<ImageButton 
    android:id="@+id/button1" 
    android:src="@drawable/btn_selector" 
    android:layout_width="200dp" 
    android:layout_height="126dp"/>