1.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="com.example.lenovo.testtogglebutton.MainActivity"> /* checked=true ToggleButton开始时显示textOn */ <ToggleButton android:checked="false" android:textOn="开" android:textOff="关" android:id="@+id/toggleButton1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/ic_launcher_foreground" /> </LinearLayout>
2.MainActivity
package com.example.lenovo.testtogglebutton;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener{
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化条件
img=(ImageView) findViewById(R.id.imageView1);
tb=(ToggleButton) findViewById(R.id.toggleButton1);
/*
给当前的tb设置监听器
*/
//写this的原因是MainActivity这个类实现了RadioGroup.OnCheckedChangeListener
tb.setOnCheckedChangeListener(this);
}
//实现CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法
@Override
public void onCheckedChanged(CompoundButton Buttonview, boolean isChecked) {
//当tb被点击的时候,当前的方法会执行
/*
Buttonview代表被点击控件的本身
isChecked代表被点击的控件的状态
当点击这个tb的时候,更换img的背景
*/
//三目运算符:isChecked为true时是preview图片,为false是ic_launcher_foreground图片,这两张图片都在drawable文件夹下
img.setBackgroundResource(isChecked?R.drawable.preview:R.drawable.ic_launcher_foreground);
}
}