switch按钮 打开和关闭
step1: 点击事件
package com.example.switchdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch switchRad = (Switch) findViewById(R.id.switch1);
switchRad.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
Toast.makeText(getBaseContext(), "TRUE", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "FALSE", Toast.LENGTH_SHORT).show();
}
}
});
}
}
step2: 布局
<?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="vertical">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:text="@string/app_name" />
</LinearLayout>
end