【发布时间】:2010-10-22 11:40:46
【问题描述】:
我想创建自定义 ImageButton,但要像开/关按钮一样工作。单击按钮图像时更改为已按下(直到按下另一个按钮)!
打开图片 本月按钮打开,今年关闭。
如何创建这样的按钮?
我需要使用以及如何使用?
谢谢
【问题讨论】:
标签: android
我想创建自定义 ImageButton,但要像开/关按钮一样工作。单击按钮图像时更改为已按下(直到按下另一个按钮)!
打开图片 本月按钮打开,今年关闭。
如何创建这样的按钮?
我需要使用以及如何使用?
谢谢
【问题讨论】:
标签: android
使用选择器 XML 标记来帮助您实现这一目标。在这里,请参阅有关 StateListDrawables 的 this 链接。所以他们的例子表明
一个 button.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
然后将实际按钮链接到该 xml:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/button" />
【讨论】:
ToggleButton 在这种情况下会更好。 d.android.com/reference/android/widget/ToggleButton.html
谢尔盖·格洛托夫和小麦感谢您的帮助
对于每个 ImageButton,我为默认和按下状态创建单独的选择器,我在 xml 中创建 ImageButton:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/month_button"
android:id="@+id/btnMonth"
android:onClick=ButonMonthClick"/>
我以编程方式更改所有 ImageButton 的 onClick 事件:
btnWeek.setBackgroundResource(R.drawable.week_pressed);
btnMonth.setBackgroundResource(R.drawable.month_default);
解决我的问题!
【讨论】: