Functions, special attributes, and usage of ToggleButton in Android self-learning notes
1. ToggleButton attributes:
1> two States are available: select and unselected states, and set different display texts for different states.
2> android: checked = true
3> android: textOff = off (default status)
4> android: textOn = on
2. Usage: (example)
Public class MainActivity extends Activity implements onCheckedChangeListener {
1> initialize the control
2> assign values to controls
3> set listeners for controls
4> override the onCheckedChanged () method {
// When the control is clicked, isChecked indicates the status of the clicked control.
ImageView. setBackGroundResource (isChecked? R. drawable. on: R. drawable. off );
}
}
Next, let's take a look at the implementation of the specific code: For the convenience of viewing, I set two images, one for opening and two for turning off.
First, activity_main.xml
Last: MainActivity. class
Package com. example. administrator. togglebutton1; import android. content. dialogInterface; import android. media. image; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. view. menu; import android. view. menuItem; import android. widget. compoundButton; import android. widget. imageView; import android. widget. toggleButton; public class MainActivity extends ActionBarActivity impl Ements CompoundButton. onCheckedChangeListener {private ToggleButton tb; private ImageView img; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); tb = (ToggleButton) findViewById (R. id. toggleButton); // initialize img = (ImageView) findViewById (R. id. imageView); tb. setOnCheckedChangeListener (this); // set the listener for the control} @ Overrid E public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {// rewrite the onCheckedChanged () method // execute when the control is clicked. isChecked indicates the status of the clicked control img. setBackgroundResource (isChecked? R. drawable. on: R. drawable. ic_adc );}}