The status of the ToggleButton can only be checked and unchecked, and different display text needs to be set for different states.
The following case is the use of ToggleButton
Directory structure
Main.xml Layout file
Copy Code code as follows:
<?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/bulb_off"
android:layout_gravity= "Center_horizontal"/>
<togglebutton android:id= "@+id/togglebutton"
Android:layout_width= "140dip"
android:layout_height= "Wrap_content"
Android:texton= "Turn on the Light"
Android:textoff= "Turn Off the Lights"
android:layout_gravity= "Center_horizontal"/>
</LinearLayout>
Togglebuttonactivity Class
Copy Code code as follows:
Package COM.LJQ.TB;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.widget.CompoundButton;
Import Android.widget.ImageView;
Import Android.widget.ToggleButton;
Import Android.widget.CompoundButton.OnCheckedChangeListener;
public class Togglebuttonactivity extends activity {
private imageview imageview=null;
private ToggleButton Togglebutton=null;
@Override
public void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.layout.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.bulb_on:r.drawable.bulb_off);
}
});
}
}
Operation effect: