demo4无法在模拟器运行,其他项目可以
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<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/off"
/>
</LinearLayout>
package com.example.demo4;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnCheckedChangeListener{
private ToggleButton tb;
private ImageButton img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb = (ToggleButton) findViewById(R.id.toggleButton1);
img = (ImageButton) findViewById(R.id.imageView1);
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 当tb被点击的时候,当前的方法会执行,buttonView代表被点击控件的本身(id)
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}