2014-12-07 113 views
0

我使用自定義的可繪製代替按鈕。例如,camButton可打開本機,以便用戶拍照。根據輸入以編程方式設置可繪製狀態

camButton提供了資源,因此drawable可以是白色或綠色。這是camButton應如何表現:

1)默認的無輸入狀態爲白色。

2)提供輸入的狀態爲綠色。 如果用戶成功拍攝了一張照片並且未將其刪除,則繪圖爲綠色以指示此情況。

3)按下按鈕時,它應該是綠色,直到用戶釋放按鈕。

4)按下按鈕時,它是綠色什麼都不做。

下面是一個selector來測試類似的東西。但是這個選擇器只會在按下按鈕時改變按鈕的顏色。它涉及上面的#1和#3,但不是#2或#4。

cam_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- green --> <item android:drawable="@drawable/cam_pressed" android:state_pressed="true"/> 
    <!-- green --> <item android:drawable="@drawable/cam_pressed" android:state_long_pressable="true"/> 
    <!-- white --> <item android:drawable="@drawable/cam_normal"/> 
</selector> 

這是選擇如何在我的主要佈局實現:

<Button 
    android:id="@+id/camButton" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:background="@drawable/cam_selector"/> 

在我的應用程序,我測試一下,看看是否有使用布爾提供的輸入。

問:我如何設置的camButton@drawable/cam_pressed根據我在代碼中的布爾(或其他方式)的狀態?

如果我不清楚,或者您需要更多信息,請讓我知道。任何建議表示讚賞。謝謝!

回答

2
Button button = (Button) findViewById(R.id.camButton);  
if(camPressed){ 
    button.setBackground(getResources().getDrawable(R.drawable.cam_pressed)) 
} else{ 
    //other stuff 
} 
相關問題