//java文件
public class MainActivity extends ActionBarActivity{
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.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
});
}
//布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bubble.MainActivity$PlaceholderFragment"
android:orientation="vertical" >
<ToggleButton
android:textOff="关灯"
android:textOn="开灯"
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:src="@drawable/off" />
</LinearLayout>
//错误信息