2010-11-24 157 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