MainActivity.java package com.test.testtogglebutton;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.CompoundButton;import android.widget.ImageView;import android.widget.ToggleButton;public clas
package com.test.testtogglebutton; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { private ToggleButton tb; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); // 初始化 tb = (ToggleButton) findViewById(R.id.toggleButton); img = (ImageView) findViewById(R.id.imageView); // 监听TB tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // 当TB被点击的时候当前的方法会被执行 // buttonView代表被点击控件的本身 // isChecked表示被点击的状态 img.setImageResource(isChecked?R.mipmap.on:R.mipmap.off); } }); } }layout.xml