【问题标题】:How to set a button in on and off state ( on and off image)如何将按钮设置为开和关状态(开和关图像)
【发布时间】:2013-05-20 19:41:18
【问题描述】:

我是 android 新手并使用以下代码,我正在尝试设置一个默认图像按钮,当单击该按钮时会切换到打开状态,直到再次按下或点击屏幕上的任何其他位置,以便与 on 关联的弹出窗口状态消失。 这是代码: java代码:

private void setOnclickListeners(View view){
        ImageButton button = (ImageButton) view.findViewById(R.id.menu_button);
        button.setOnClickListener(this);
    }

我想将此代码连接到以下等触发和关闭状态:

<ImageButton
            android:id="@+id/menu_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@android:color/transparent"
            android:paddingRight="8dp"
            android:src="@drawable/menu_btn" />

这是 xml 类的 menu_btn 代码:

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/menu_on"/>
<item android:state_pressed="true" android:drawable="@drawable/menu_on" />
<item android:drawable="@drawable/menu_off" />  
</selector>

有什么办法吗?蚂蚁帮助表示赞赏。谢谢!贾斯汀

【问题讨论】:

  • toggleButton 不是更好的选择吗?
  • 没有线索?你能编辑我的切换按钮代码并展示它是如何工作的吗?谢谢!

标签: android android-layout android-intent android-emulator android-listview


【解决方案1】:

您可能需要检查ToggleButton(或Checkable 的任何子类)以了解您的实现,然后将其状态设置为类似这样,

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@drawable/menu_off"/>
    <item android:state_checked="true" android:drawable="@drawable/menu_on" />
    <item android:drawable="@drawable/menu_off" />  
</selector>

然后在您的 Java 代码上,获取您的 ToggleButton(或 Checkable)实例,并根据您的操作更新 setChecked 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2014-06-16
    • 2016-08-24
    相关资源
    最近更新 更多