开关键

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"
      tools:context=".MainActivity">>
  
      <ToggleButton
          android:id="@+id/tbt_open"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textOn="On"
          android:textOff="Off"   
          />
  
      <Switch
          android:id="@+id/sbt_open"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textOn="ON"
          android:textOff="OFF"/>
  
  </LinearLayout>
  

MainActivity.java

      package com.davis.togglebutton;
      
      import androidx.appcompat.app.AppCompatActivity;
      
      import android.os.Bundle;
      import android.widget.CompoundButton;
      import android.widget.Switch;
      import android.widget.Toast;
      import android.widget.ToggleButton;
      
      public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
      
          ToggleButton tbt_open;
          Switch stb_open;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              tbt_open = (ToggleButton) findViewById(R.id.tbt_open);
              stb_open = (Switch) findViewById(R.id.sbt_open);
              tbt_open.setOnCheckedChangeListener(this);
              stb_open.setOnCheckedChangeListener(this);
      
          }
      
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              switch (buttonView.getId()) {
                  case R.id.tbt_open:
                      if (buttonView.isChecked()) {
                          Toast.makeText(this, "打开声音", Toast.LENGTH_SHORT).show();
                      } else Toast.makeText(this, "关闭声音", Toast.LENGTH_SHORT).show();
                      break;
      
                  case R.id.sbt_open:
                      if (buttonView.isChecked())
                          Toast.makeText(this, "开关:ON", Toast.LENGTH_SHORT).show();
                      else Toast.makeText(this, "开关:OFF", Toast.LENGTH_SHORT).show();
                      break;
              }
      
          }
      }