<?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:id="@+id/containt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ToggleButton
android:checked="false"
android:textOn="开"
android:textOff="关"
android:id="@+id/toggleButoon"
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/baby"/>
</LinearLayout>
package com.example.youyou;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
//1.初始化变量
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2.初始化控件
tb=(ToggleButton)findViewById(R.id.toggleButoon);
img=(ImageView)findViewById(R.id.imageView1);
/*
3.给tb设置监听器
*/
tb.setOnCheckedChangeListener(this);
}
/*
当tb被点击 当前方法会被执行
buttonView-----代表被点击控件本身
isChecked------代表被点击控件的状态
*/
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){
img.setBackgroundResource(isChecked?R.drawable.baby:R.drawable.head);
}
}