我有一个具有两种状态(选中和未选中)的按钮。按钮的图像因州而异。我应该使用哪一个?如何设置图像和状态?请提出建议(我是android的新手)。
最佳答案
在 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。
关于android - 我应该使用什么 ImageButton 或 Button?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4264851/