2013-02-06 125 views
0

我有幾個ImageButtons,我試圖強制其中一個行爲像CheckBox。當用戶按下按鈕時,我想將按鈕的背景切換爲「按下」(橙色,就像您點擊並按住)和「正常」狀態之間。如何做到這一點?下面的代碼並不是真的這樣做。以編程方式設置ImageButton狀態

public void btnErase_click(View v) { 
     ImageButton btnErase = (ImageButton) findViewById(R.id.btnErase); 
     if (pressed == true) 
      btnErase.setBackgroundColor(Color.YELLOW); 
     else   
      btnErase.setBackgroundColor(android.R.drawable.btn_default); 
    } 
+0

什麼做你的代碼呢? –

+0

您是否考慮過使用ToggleButton並使用XML drawables指定其選中/未選中的外觀?而不是試圖通過您自己的代碼使ImageButton像ToggleButton一樣運行。 – CloudyMusic

+0

我有幾個按鈕,我想在風格上看起來很相似。其中只有一個應該有不同的表現。我會嘗試使用ToggleButton並查看它是否與ImageButton類似。 –

回答

1

您應該使用傳入的View v,無需再次找到ImageButton。

此外,如果你設置的按鈕,背景圖像使用setBackgroundResource,而不是setBackgroundColor

public void btnErase_click(View v) { 
     ImageButton btnErase = (ImageButton) v; 
     if (pressed == true) 
      btnErase.setBackgroundColor(Color.YELLOW); 
     else   
      btnErase.setBackgroundResource(android.R.drawable.btn_default); 
    } 
+0

謝謝! setBackgroundResource解決了我一半的問題。現在我可以將其設置回「正常」外觀。 –

1

你應該else子句中使用setBackgroundResource,而不是setBackgroundCOlor。因爲android.R.drawable.btn_defaul不是顏色,所以它是資源的ID。

+0

我的錯。確實setBackgroundResource是調用的正確函數。 –

1

你可以試試這個可能是通過XML來設置不同的狀態,它保存在可繪製,然後將其設置爲背景,以您的按鈕:

<item android:state_pressed="true"><shape> 
     <solid android:color="#3c3c3c" /> 

     <stroke android:width="0.5dp" android:color="#3399cc" /> 

     <corners android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp" android:topLeftRadius="4dp" android:topRightRadius="4dp" /> 

     <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" /> 
    </shape></item> 
<item><shape> 
     <gradient android:angle="270" android:endColor="#171717" android:startColor="#505050" /> 

     <stroke android:width="0.5dp" android:color="#3399cc" /> 

     <corners android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp" android:topLeftRadius="4dp" android:topRightRadius="4dp" /> 

     <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" /> 
    </shape></item> 

1

首先,提供選擇器。將其另存爲繪圖/ button_bg.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 

    <item android:state_checked="true" android:drawable="@android:color/yellow" /> 
    <item drawable="@android:drawable/btn_default" /> 

</selector> 

將其應用於您的按鈕作爲背景。 在代碼

public void btnErase_click(View v) { 
    ImageButton btnErase = (ImageButton) findViewById(R.id.btnErase); 
    if (pressed) { 
     btnErase.getBackground().setState(new int[]{android.R.attr.state_selected}); 
    } else { 
     btnErase.getBackground().setState(new int[]{-android.R.attr.state_selected}); 
    } 
} 

但我不認爲這是一個好主意。如果你的按鈕有兩個狀態更好使用ToggleButton

相關問題