状态开关(ToggleButton)

状态开关(ToggleButton):

常用属性:isChecked(是否被选中,如true)

监听:1.监听方法:setOnCheckedChangeListener

   2.监听器:CompoundButton.OnCheckedChangeListener

1.Activity

//状态的开关
public class ToggleButtonActivity extends Activity {

    private ToggleButton toggleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toggle_button);
        
        toggleButton = (ToggleButton)findViewById(R.id.toggleButtonId);
        
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    Toast.makeText(ToggleButtonActivity.this, "无线网络打开了!", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(ToggleButtonActivity.this, "无线网络关闭了!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

2.xml文件

<?xml version="1.0" encoding="utf-8"?>
<!-- 状态的开关页面 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="无线网:"
        android:textSize="20sp" />

    <ToggleButton
        android:id="@+id/toggleButtonId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

3.效果显示图

原文地址:https://www.cnblogs.com/wuziyue/p/5470376.html