package com.demo2.demo2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnCheckedChangeListener{
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tb=(ToggleButton)findViewById(R.id.toggleButton1);
img=(ImageView)findViewById(R.id.imageView1);
/*
* 给当前的tb设置监听器
*/
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*
* 当tb被点击的时候,当前的方法会执行
*
* buttonView代表被点击空间的本身
* isChecked代表被点击的空间的状态
*
* 当点击这个tb的时候,更换img的背景
*/
img.setBackgroundResource(isChecked?R.drawable.touxiang:R.drawable.lena);
}
}
<?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" >
<!--textOn:true textOff:false-->
<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/lena"
/>
</LinearLayout>