Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a Lollipop switch button

Tags:

I want to have the Lollipop style switch button for my app:

enter image description here

How could I implement this button so it looks like this also on older versions of android?

like image 344
stoefln Avatar asked Apr 20 '15 15:04

stoefln


2 Answers

To have the Lollipop style switch button on older versions of android you should use SwitchCompat in layout xml file

<android.support.v7.widget.SwitchCompat         android:id="@+id/compatSwitch"         android:layout_width="wrap_content"         android:layout_height="wrap_content"/> 

and also in java file

SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.compatSwitch); 
like image 136
dzikovskyy Avatar answered Oct 27 '22 00:10

dzikovskyy


At first set android:targetSdkVersion="22" in your manifest to make your app compatible to Lollipop.

NOTE: Color of your switch depends on this

<item name="android:colorAccent">@color/accent</item> 

Create your own theme for your app in styles.xml in Folder values-v21

<?xml version="1.0" encoding="utf-8"?> <resources>     <style name="AppTheme" parent="AppTheme.Base">         <item name="android:colorPrimary">@color/primary</item>         <item name="android:colorPrimaryDark">@color/primary_dark</item>         <item name="android:colorAccent">@color/accent</item>         <item name="android:textColorPrimary">@color/text_primary</item>         <item name="android:textColor">@color/text_secondary</item>         <item name="android:navigationBarColor">@color/primary_dark</item>         <item name="toolbarStyle">@style/Widget.AppCompat.Toolbar</item>     </style> </resources> 

styles.xml in default Folder values or values-v14

<resources>      <!-- Base application theme. -->     <style name="AppTheme" parent="AppTheme.Base">         <!-- Customize your theme here. -->          <item name="toolbarStyle">@style/Widget.AppCompat.Toolbar</item>     </style>      <style name="AppTheme.Base" parent="Theme.AppCompat">         <!-- Customize your theme here. -->          <!-- colorPrimary is used for the default action bar background -->         <item name="colorPrimary">@color/primary</item>          <!-- colorPrimaryDark is used for the status bar -->         <item name="colorPrimaryDark">@color/primary_dark</item>          <!-- colorAccent is used as the default value for colorControlActivated              which is used to tint widgets -->         <item name="colorAccent">@color/accent</item>          <!-- You can also set colorControlNormal, colorControlActivated              colorControlHighlight & colorSwitchThumbNormal. -->     </style>  </resources> 
like image 44
ch3tanz Avatar answered Oct 27 '22 00:10

ch3tanz