【问题标题】:Android custom image on/off buttonAndroid 自定义图像开/关按钮
【发布时间】:2010-10-22 11:40:46
【问题描述】:

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

打开图片 本月按钮打开,今年关闭。

如何创建这样的按钮?

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

谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    使用选择器 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
    • @Sergey Glotov 切换按钮是一个中间贴有“灯”的按钮。如果您希望在单击时使用带有自定义图形的自定义按钮,则必须使用选择器。我经常错。如果您知道更多,请发布解决方案。我也很想看看。我自己还在学习 Android。
    • 但是选择器没有保存它的状态?
    • 我尝试了不同的方法,我认为 Sergey Glotov 是正确的“选择器不保存其状态”。我的解决方案在上面
    【解决方案2】:

    谢尔盖·格洛托夫和小麦感谢您的帮助

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

    解决我的问题!

    【讨论】:

    • 不要手动更改资源。这就是选择器的用途。请参阅@wheaties 答案。
    • 但我想要“点击按钮时,图像被更改为按下(直到按下另一个按钮)”但选择器不保存其状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2014-07-18
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多