我应该使用ImageButton还是Button?

10

我有一个有两个状态(选中和未选中)的按钮。每个状态下按钮的图片都不同。我应该使用哪个?我该如何设置图片和状态?请给些建议(我是Android开发新手)。

1个回答

14

在drawable文件夹中使用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。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接