//安卓中ToggleButton的使用,配合单选效果,点击变化视图的切换效果
public class MainActivity extends Activity {
private ImageView imageView=null;
private ToggleButton toggleButton=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView) findViewById(R.id.imageView);
toggleButton=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
toggleButton.setChecked(isChecked);
imageView.setImageResource(isChecked?R.drawable.p1:R.drawable.p3);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/p3"
android:layout_gravity="center_horizontal" />
<ToggleButton android:id="@+id/toggleButton"
android:layout_width="140dip"
android:layout_height="wrap_content"
android:textOn="开灯"
android:textOff="关灯"
android:layout_gravity="center_horizontal" />
</LinearLayout>