summaryrefslogtreecommitdiff
path: root/docs/html/guide/topics/ui/controls/togglebutton.jd
blob: 181647c218495a6c2baac2562ad289720c7aa883 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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.support.v7.widget.SwitchCompat}</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.
{@link android.support.v7.widget.SwitchCompat} is a version of the Switch
widget which runs on devices back to API 7.</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>