Files
frameworks_base/docs/html/guide/topics/ui/controls/togglebutton.jd
Andrew Solovay 07e7021e06 docs: Clarified how to find out when a switch is toggled
Per Chris, the existing doc was incorrect: you *can't* check for a
button press and a switch flip the same way. (The button triggers a
click event, but the switch does not.) Chris suggested that we just
remove the reference to onClick and suggest using a listener for
both kinds of buttons (ToggleButton and Switch).

Also pulled one note out of a section where it didn't fit (the bit
about changing a button/switch's state programmatically didn't have
much to do with listening for clicks) and put it at the top, and I
fixed a Javadoc typo for a relevant class that I happened to notice.

See first comment for doc stage location.

bug: 20625504
Change-Id: I9c8975111381e5b169f6a61454ef3a93da635759
2015-07-09 13:22:31 -07:00

66 lines
2.0 KiB
Plaintext

page.title=Toggle Buttons
page.tags=switch,togglebutton
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li>
<a href="#ClickListener">Responding to Button Presses</a>
</li>
</ol>
<h2>Key classes</h2>
<ol>
<li>{@link android.widget.ToggleButton}</li>
<li>{@link android.widget.Switch}</li>
<li>{@link android.widget.CompoundButton}</li>
</ol>
</div>
</div>
<p>A toggle button allows the user to change a setting between two states.</p>
<p>You can add a basic toggle button to your layout with the {@link android.widget.ToggleButton}
object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that
provides a slider control, which you can add with a {@link android.widget.Switch} object.</p>
<p>
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.
</p>
<div style="float:left;width:200px">
<img src="{@docRoot}images/ui/togglebutton.png" alt="" />
<p class="img-caption"><em>Toggle buttons</em></p>
</div>
<div style="float:left;width:200px;margin-top:24px">
<img src="{@docRoot}images/ui/switch.png" alt="" />
<p class="img-caption"><em>Switches (in Android 4.0+)</em></p>
</div>
<h2 id="ClickListener">Responding to Button Presses</h2>
<p>
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:
</p>
<pre>
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
</pre>