Wednesday, January 2, 2013

7 How to create custom Switch in Android


From Developer.android.com: “A Switch is a two-state toggle switch widget that can select between two options. The user may drag the "thumb" back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox. The text property controls the text displayed in the label for the switch, whereas the off and on text controls the text on the thumb…”

In this tutorial, we show you how to customize a Switch, add a click listener and get the setOnCheckedChangeListener for this Switch. Use Switch to control with media volume and wifi on device.

Here is a result of this tutorial:

Android Custom Switch Control

This project is developed in Eclipse 4.2.0.
1. First, modify the main layout of app. Open “res/layout/main.xml” file, add two switches, few textviews and a button.



<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Disable all switch"
        android:layout_marginBottom="15dp"
            android:onClick="button_click"/>
   
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
           
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toLeftOf="@+id/switch1"
                android:layout_alignParentLeft="true"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="20dp"
                android:text="Media Volume"/>
            <Switch
                android:id="@+id/switch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOff="OFF"
                android:textOn="ON"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:onClick="onSwitchClicked"
                android:thumb="@drawable/switch_bg"
                android:track="@drawable/track_bg"
                android:layout_marginBottom="15dp" />  
               
            <TextView android:layout_below="@+id/switch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toLeftOf="@+id/switch2"
                android:layout_alignParentLeft="true"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="20dp"
                android:text="Wifi"/>
            <Switch android:layout_below="@+id/switch1"
                android:id="@+id/switch2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOff="OFF"
                android:textOn="ON"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:onClick="onSwitchClicked"
                android:thumb="@drawable/switch_bg"
                android:track="@drawable/track_bg"
                android:layout_marginBottom="15dp" />  
        </RelativeLayout>
        <TextView android:id="@+id/textView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="27px"
                android:layout_marginTop="15dp"
                android:text="Show spinner choice"
                android:gravity="center"
                android:textColor="#CD2134" 
                android:textStyle="bold"  />
</LinearLayout>
Note two attribute of Switch below:
                android:thumb="@drawable/switch_bg"
                android:track="@drawable/track_bg"

We need two xml files “switch_bg.xml” and “track_bg.xml” in folder drawable to customize for all switches:
res/drawable/switch_bg:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/enable" />
    <item android:state_pressed="true"  android:drawable="@drawable/press" />
    <item android:state_checked="true"  android:drawable="@drawable/check_on" />
    <item                               android:drawable="@drawable/enable" />
</selector>
res/drawable/track_bg:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/track_disable" />
    <item                               android:drawable="@drawable/track_default" />
</selector>

2. CODE.
2.1. Add click listener to all Switches
Use  android:onClick attribute in the Switch  XML definition:
android:onClick="onSwitchClicked "

Within the activity that hosts this layout, the following method handles the click event for all switches, one switch for ON/OFF Media Volume, and one for ON/OFF Wifi on device.

public void onSwitchClicked(View view) {
        switch(view.getId()){
        case R.id.switch1:
                if(switch1.isChecked()) {
                textview.setText("Switch 1 check ON by click on it"); 
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        8, 0);
                }
                else {
                textview.setText("Switch 1 check OFF by click on it");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        0, 0);
                }
                break;
            case R.id.switch2:
                        if(switch2.isChecked()) {
                        textview.setText("Switch 2 check ON by click on it");
                        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                        wifiManager.setWifiEnabled(true);
                        }
                else {
                        textview.setText("Switch 2 check OFF by click on it");
                        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                        wifiManager.setWifiEnabled(false);
                }
                        break;
                }
    }

2.2. How to get the setOnCheckedChangeListener for Switch. This method is executed when the User drag the thumb or click on the Switch, and then do similar with onClick method of this Switch

switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
            if (buttonView.isChecked()){
                textview.setText("Switch 1 check ON by drag thumb");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 8, 0);                                  }
            else{
                textview.setText("Switch 1 check OFF by drag thumb");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            }
        }
});
       
switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
            if (buttonView.isChecked()){
                textview.setText("Switch 2 check ON by drag thumb");
                wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                wifiManager.setWifiEnabled(true);
            }
            else{
                textview.setText("Switch 2 check OFF by drag thumb");
                wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                        wifiManager.setWifiEnabled(false);
            }
        }
});

2.3. Finally, add button onClick method to enable or disable all Switches

public void button_click(View view){
        if(is_enable == true)
        {
                is_enable = false;
                button.setText("Enable all switch");
                        textview.setText("Switch is Disable by click on button");
        }
        else{
                is_enable = true;
                button.setText("Disable all switch");
                textview.setText("Switch is Enable by click on button");
        }
        switch1.setEnabled(is_enable);
        switch2.setEnabled(is_enable);
    }
Note: to work with wifi on device, you want to add some permission in AndroidManifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

3. DEMO
3.1. Run Application

Android Custom Switch Control

3.2. When click on Switch 1 to ON/OFF Media Volume of device

Android Custom Switch Control
  
3.3. When drag thumb on Switch 2 to ON/OF Wifi

Android Custom Switch Control

4.4. Click on button to Enable or Disable all Switches

Android Custom Switch Control

You can download all source codes of this tutorial from here
Reference: http://developer.android.com/reference/android/widget/Switch.html

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi, great post! Thanks. I can't get any of the styles to change. I've tried track, thumb, textOn, textOff and nothing changes. Can you think of anything I may be doing wrong? Thanks again.

    ReplyDelete
  3. hi...Im student from Informatics engineering nice article,
    thanks for sharing :)

    ReplyDelete
  4. Hello,

    I'm wondering if for your drawables such as drawable/enabled you're using your own defined xml files, or if you're using an image of some sort. If you are using an xml file is there any chance I could get a look at a sample version of it?

    Thanks,

    ReplyDelete
  5. Hello,
    Same here,
    Wanted to know what your xml files were for the drawables for the switch_bng and the track_bng.
    Cheers

    ReplyDelete
  6. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai | Best Android Training in chennai|Android Training in chennai with placement | Android Training in velachery

    ReplyDelete