Home | History | Annotate | Download | only in controls
      1 page.title=Toggle Buttons
      2 page.tags=switch,togglebutton
      3 @jd:body
      4 
      5 <div id="qv-wrapper">
      6 <div id="qv">
      7 <h2>In this document</h2>
      8 <ol>
      9   <li>
     10     <a href="#ClickListener">Responding to Button Presses</a>
     11   </li>
     12 </ol>
     13   <h2>Key classes</h2>
     14   <ol>
     15     <li>{@link android.widget.ToggleButton}</li>
     16     <li>{@link android.widget.Switch}</li>
     17     <li>{@link android.support.v7.widget.SwitchCompat}</li>
     18     <li>{@link android.widget.CompoundButton}</li>
     19   </ol>
     20 </div>
     21 </div>
     22 
     23 <p>A toggle button allows the user to change a setting between two states.</p>
     24 
     25 <p>You can add a basic toggle button to your layout with the
     26 {@link android.widget.ToggleButton} object. Android 4.0 (API level 14)
     27 introduces another kind of toggle button called a switch that provides a slider
     28 control, which you can add with a {@link android.widget.Switch} object.
     29 {@link android.support.v7.widget.SwitchCompat} is a version of the Switch
     30 widget which runs on devices back to API 7.</p>
     31 
     32 <p>
     33   If you need to change a button's state yourself, you can use the {@link
     34   android.widget.CompoundButton#setChecked CompoundButton.setChecked()} or
     35   {@link android.widget.CompoundButton#toggle CompoundButton.toggle()} methods.
     36 </p>
     37 
     38 <div style="float:left;width:200px">
     39 <img src="{@docRoot}images/ui/togglebutton.png" alt="" />
     40 <p class="img-caption"><em>Toggle buttons</em></p>
     41 </div>
     42 
     43 <div style="float:left;width:200px;margin-top:24px">
     44 <img src="{@docRoot}images/ui/switch.png" alt="" />
     45 <p class="img-caption"><em>Switches (in Android 4.0+)</em></p>
     46 </div>
     47 
     48 <h2 id="ClickListener">Responding to Button Presses</h2>
     49 
     50 <p>
     51   To detect when the user activates the button or switch, create an {@link
     52   android.widget.CompoundButton.OnCheckedChangeListener} object and assign it
     53   to the button by calling {@link
     54   android.widget.CompoundButton#setOnCheckedChangeListener
     55   setOnCheckedChangeListener()}. For example:
     56 </p>
     57 
     58 <pre>
     59 ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
     60 toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
     61     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
     62         if (isChecked) {
     63             // The toggle is enabled
     64         } else {
     65             // The toggle is disabled
     66         }
     67     }
     68 });
     69 </pre>
     70