Labels

‘Google Play again alcohol analytics Android Android Control Android Developer Android ebook Android N Android Studio Android Wear AndroidDevStory androidn AndroidWear anime Apps average bag beach benidorm beta testing betatesting GooglePlayforFamilies birthday BLT buildingforbillions camden camera cat ears charm christmas Christmas Countdown Clock chrome circle lenses Clock coat coffee collar Connectivity cosplay Countdown craft CultureAlley curl cute Develop Developer Preview developerstory developerstory developerconsole Distribute DIY drunk Education engagement exhibition families fashion Featured Featured’ felt fox freshers friends funny Games geek ghibli Google I/O Google Play Google Play Games Google Play games services GooglePlay gothic lolita gyaru hair halloween hand made hangover happy harry belafonte havea HelloEnglish herbie hancock hiragana Hitman Reborn holiday home hood hoodie hot chocolate house Hutch i'm back instagram iOS Control japanese japanese lolita javea kawaii kawaii it yourself kitty and the bulldog KIY knitting la mort learning life lightning lolita london look love love lunch machine madoka kaname maid maid cafe make-up make-up tutorial mariscos recio MaterialDesign me medieval mobile vision APIs monetization museum music Naruto Clock Naruto Flash Game NBU NDK needles neko nerd new New Year Countdown Clock oh One Piece Flash Clock Onee-chan outfit owl pan party peter peter pan photography pink player pool punk lolita purikura Reborn record red riding hood sea Security sewing shoes sorry spain store listing experiments story Storytoys student sunny sunshine sweet lolita table football tail tan to today totoro trying tutorial Udacity uni vam VandA victoria and albert vinyl wear well wifi wig winter wool xabia yarn zombie

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 setOnCheckedChangeListenerfor 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(newCompoundButton.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

0 Response to "How to create custom Switch in Android"

Post a Comment