ToggleButton 只有两种状态,on/off 可以自己设置状态的文字。有Click和CheckedChange两种事件。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.w2_15);
final ImageView iv = (ImageView) findViewById(R.id.w2_15_iv1) ;
ToggleButton tb1 = (ToggleButton) findViewById(R.id.w2_15_tb1) ;
tb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
iv.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off) ;
}
}) ;
}
xml
<?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" >
<ImageView
android:id="@+id/w2_15_iv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<ToggleButton
android:id="@+id/w2_15_tb1"
android:textOn="On"
android:textOff="Off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</LinearLayout>