I. Overview
ToggleButton has two states: checked and unchecked (similar to a switch), and you need to set different display text for different states
Second, ToggleButton properties
android:checked = "true"--the State of the button (True is checked (Texton), False is unchecked (Textoff))
Android:textoff = "Off"
Android:texton = "Open"
Three, the code demonstration
1, first put the following two pictures into the resource file (named off and on)
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "vertical" > <ToggleButtonAndroid:id= "@+id/togglebutton1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:texton= "Open"Android:textoff= "Off" /> <ImageViewAndroid:id= "@+id/imageview1"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:src= "@drawable/off" /> </LinearLayout>
PackageCom.muke.textview_edittext;ImportAndroid.os.Bundle;ImportAndroid.widget.CompoundButton;ImportAndroid.widget.CompoundButton.OnCheckedChangeListener;ImportAndroid.widget.ImageView;ImportAndroid.widget.ToggleButton;Importandroid.app.Activity; Public classMainactivityextendsActivityImplementsoncheckedchangelistener{PrivateToggleButton TB; PrivateImageView img; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //First step: Initialize the control (find the control you want to manipulate)TB =(ToggleButton) Findviewbyid (R.id.togglebutton1); IMG=(ImageView) Findviewbyid (R.ID.IMAGEVIEW1); //to set the listener for the current TB controlTb.setoncheckedchangelistener ( This); } @Override Public voidOnCheckedChanged (Compoundbutton Buttonview,BooleanisChecked) { //when the TB is clicked, the current method executes//buttonview--represents the clicked control itself//ischecked--represents the state of the control being clicked//when you click on TB this control is better img srcImg.setimageresource (isChecked? R.drawable.on:r.drawable.off);//set the SRC path of the ImageView control in Java code (here you use the ternary operation to set the path to the picture) }}
Android Control ToggleButton (Multi-Status button)