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