From 07e7021e062dd3579f662502b15c0682c4672cfe Mon Sep 17 00:00:00 2001
From: Andrew Solovay In this document
Key classes
+ If you need to change a button's state yourself, you can use the {@link + android.widget.CompoundButton#setChecked CompoundButton.setChecked()} or + {@link android.widget.CompoundButton#toggle CompoundButton.toggle()} methods. +
+The {@link android.widget.ToggleButton} and {@link android.widget.Switch} -controls are subclasses of {@link android.widget.CompoundButton} and function in the same manner, so -you can implement their behavior the same way.
- -When the user selects a {@link android.widget.ToggleButton} and {@link android.widget.Switch}, -the object receives an on-click event.
- -To define the click event handler, add the android:onClick
attribute to the
-<ToggleButton>
or <Switch>
element in your XML
-layout. The value for this attribute must be the name of the method you want to call in response
-to a click event. The {@link android.app.Activity} hosting the layout must then implement the
-corresponding method.
For example, here's a {@link android.widget.ToggleButton} with the android:onClick
attribute:
-<ToggleButton - android:id="@+id/togglebutton" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:textOn="Vibrate on" - android:textOff="Vibrate off" - android:onClick="onToggleClicked"/> -- -
Within the {@link android.app.Activity} that hosts this layout, the following method handles the -click event:
- --public void onToggleClicked(View view) { - // Is the toggle on? - boolean on = ((ToggleButton) view).isChecked(); - - if (on) { - // Enable vibrate - } else { - // Disable vibrate - } -} -- -
The method you declare in the {@link android.R.attr#onClick android:onClick} attribute -must have a signature exactly as shown above. Specifically, the method must:
-Tip: If you need to change the state -yourself, -use the {@link android.widget.CompoundButton#setChecked(boolean)} or {@link -android.widget.CompoundButton#toggle()} method to change the state.
- - - -You can also declare a click event handler programmatically rather than in an XML layout. This -might be necessary if you instantiate the {@link android.widget.ToggleButton} or {@link -android.widget.Switch} at runtime or you need to -declare the click behavior in a {@link android.app.Fragment} subclass.
+To declare the event handler programmatically, create an {@link -android.widget.CompoundButton.OnCheckedChangeListener} object and assign it to the button by calling -{@link -android.widget.CompoundButton#setOnCheckedChangeListener}. For example:
++ To detect when the user activates the button or switch, create an {@link + android.widget.CompoundButton.OnCheckedChangeListener} object and assign it + to the button by calling {@link + android.widget.CompoundButton#setOnCheckedChangeListener + setOnCheckedChangeListener()}. For example: +
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton); -- cgit v1.1