ToggleButton

来源:互联网 发布:以此为政,不亦惑乎翻译 编辑:程序博客网 时间:2024/06/05 19:43

简介

ToggleButton(开关按钮)是Android系统中比较简单的一个组件,是一个具有选中和未选择状态双状态的按钮,并且需要为不同的状态设置不同的显示文本

属性名称 描述 android:disabledAlpha 这里写图片描述 android:textOff 未选中时按钮的文本 android:textOn 选中时按钮的文本

简单使用

off

on

xml

<ToggleButton    android:id="@+id/button1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:textOn="开"    android:textOff="关"    />

点击切换图片

图片贡献如下

off

on

drawable下增加toggle_button_selector.xml

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

xml

<ToggleButton    android:id="@+id/button1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:textOn=""    android:textOff=""    android:background="@drawable/toggle_button_selector"    />还可以增加    android:checked="true" 或     android:checked="false"来改变默认选中状态

java代码

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        final ToggleButton toggleButton = (ToggleButton)findViewById(R.id.button1);        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {                toggleButton.setChecked(b);            }        });    }
原创粉丝点击