Android 4.0 ICS switch button example

Switch button introduced in Android 4.0 onwards, it helps in indicating the user to Enable or Disable i.e ON/OFF  any feature/service. This toggle makes UI  simpler. In pre ICS 4.0 devices use to have checkbox.

This example shows in a single app, you can add switch button for Android 4.0 or above and for pre ICS devices use checkboxes.

1) You need to have 2 separate XML files, one for API 11 onwards and one more for earlier versions

3) In layout-V11 folder create a XML file and add toggle switch button code.

 <merge android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="" xmlns:tools="">  
   <switch android:checked="true" android:id="@+id/id_alarm_status" android:layout_centerinparent="true" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_width="wrap_content" tools:ignore="NewApi">  

4) In normal layout folder, create XML file with same name and add checkbox code.

 <merge android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="">  
  <checkbox android:checked="true" android:id="@+id/id_alarm_status" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ON" android:textsize="15sp" android:textstyle="bold">  

5) In the main layout simply include the switchbutton layout as shown below

 <relativelayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="" xmlns:tools="">  
          <include layout="@layout/switchbutton">  

Instantiate toggle button in code

CompoundButton is the parent button of the Switch & checkbox.
 CompoundButton mStatus = null;   
      protected void onCreate(Bundle savedInstanceState) {  
           mStatus = (CompoundButton)findViewById(;  

To change text in checkbox in Pre ICS devices ,

 mStatus.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
                public void onCheckedChanged(CompoundButton arg0, boolean state) {  
                     //This works for Pre ICS devices only,  
                          if(VERSION.SDK_INT &lt VERSION_CODES.ICE_CREAM_SANDWICH)  
                          if(VERSION.SDK_INT &lt VERSION_CODES.ICE_CREAM_SANDWICH)