Android自定义图像开/关按钮

时间:2010-10-22 11:40:46

标签: android

我想创建自定义ImageButton,但要像开/关按钮一样工作。点击按钮图像更改为按下(直到按下另一个按钮)!

在图片上本月按钮开启,今年关闭。

如何创建这样的按钮?

我需要使用以及如何使用?

由于

alt text

2 个答案:

答案 0 :(得分:8)

使用选择器XML标记来帮助您实现此目的。在此处,请参阅有关thisStateListDrawable链接。所以他们的例子显示了

一个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" />

答案 1 :(得分:1)

Sergey Glotov和wheaties感谢您的帮助

对于每个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);

Thant解决了我的问题!