1.ToggleButton: There are two states: checked and unchecked, and you need to set different display text for different states
2.ToggleButton property: Android:checked= "true" android:textoff= "Off" android:texton= "off"
Activity_main:
<?xml version= "1.0" encoding= "Utf-8"?>
<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:paddingbottom= "@dimen/activity_vertical_margin"
android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin"
android:paddingtop= "@dimen/activity_vertical_margin"
tools:context= "Com.example.administrator.demo2.MainActivity" >
<togglebutton
Android:id= "@+id/togglebutton1"
Android:checked= "false"
Android:textoff= "Off"
android:texton= "Open"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"/>
<imageview
Android:id= "@+id/image1"
android:background= "@drawable/off"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"/>
</RelativeLayout>
Mainactivity:
Package Com.example.administrator.demo2;
Import Android.media.Image;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.widget.CompoundButton;
Import Android.widget.ImageView;
Import Android.widget.ToggleButton;
public class Mainactivity extends appcompatactivity{
Private ToggleButton TB;
Private ImageView img;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Initializing the control
tb= (ToggleButton) Findviewbyid (R.id.togglebutton1);
Img= (ImageView) Findviewbyid (r.id.image1);
To set the listener for the current TB
Tb.setoncheckedchangelistener (New Compoundbutton.oncheckedchangelistener () {
@Override
public void OnCheckedChanged (Compoundbutton buttonview, Boolean isChecked) {
/*
When the TB is clicked, the current method is executed
Buttonview represents the clicked control itself
IsChecked represents the state of the clicked control
When you click TB, change the background of IMG
*/
Img.setbackgroundresource (isChecked? R.drawable.on:r.drawable.off);
}
});
}
}
Android Studio Development Note Three