ToggleButton

开关按钮(ToggleButton)

Toggle Button是切换按钮, 很简单,可以在两种状态中切换.我们可以通过在XML文件中添加ToggleButton对象来创建一个ToggleButton,在API14之后我们还可以添加一种新的类型的ToggleButton—Switch对象.

这是ToggleButton对象:


如果我们需要通过代码改变ToggleButton的状态,我们可以使用CompoundButton.setChecked()或者CompoundButton.toggle()方法来实现.

响应按钮点击事件

我们需要CompoundButton.OnCheckedChangeListener对象来监听ToggleButton的点击事件, 代码如下:

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});
Copyright© 2020-2022 li-xyz 冀ICP备2022001112号-1