2010-11-24 28 views
9

我有一個按鈕有兩種狀態(選中和未選中)。按鈕的圖像對於狀態是不同的。我應該使用哪一個?我如何設置圖像和狀態?請給建議(我是新來的android)。我應該使用ImageButton還是Button?

回答

14

在可繪製文件夾中使用xml配置。相反,引用的圖像作爲背景爲您的按鈕,你引用這個xml配置(文件名):

如:my_button.xml

<selector 
xmlns:android="http://schemas.android.com/apk/res/android"> 

<item 
    android:state_focused="true" 
    android:state_pressed="false" 
    android:drawable="@drawable/button_style1_active" /> 
<item 
    android:state_focused="true" 
    android:state_pressed="true" 
    android:drawable="@drawable/button_style1_down" /> 
<item 
    android:state_focused="false" 
    android:state_pressed="true" 
    android:drawable="@drawable/button_style1_down" /> 
<item 
    android:drawable="@drawable/button_style1_up" /> 

</selector> 

使用在layout.xml:

<Button android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Tap me" 
     android:background="@drawable/my_button"/> 

通過這種配置,您可以影響按鈕的外觀,按下按鈕或聚焦等。對於這兩種類型的按鈕(Button和ImageButton)都是相同的。如果您的按鈕不包含文字,請使用ImageButton。

+0

1000+爲它...工作得很好.. – xydev 2010-11-24 09:06:05

相關問題