본문 바로가기

안드로이드

switch custom

Switch 버튼은 안드로이드 API Level 14를 요구하는 고스펙중 하나이다.


기본 디자인

ON일때


OFF일때



참고 사이트

http://stackoverflow.com/questions/23358822/how-to-custom-switch-button

http://developer.android.com/intl/ko/guide/topics/ui/controls/togglebutton.html



순수코딩↓

-메모리를 조금 절약할수 있다.

주의 해야될 부분이 있다면

기본쓰면 백그라운드등 주어도 각 버전마다 다르게 들어갈수도 있습다.


ON일때 디자인


OFF일때 디자인



layout.xml

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/cm_background_gray">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:layout_margin="10dp"
android:textSize="17dp"
android:text="@string/setting_alarm_title1"/>
<Switch
android:id="@+id/alarm_all_on_bt"
style="@style/SwitchCustom"
android:layout_weight="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="20dp"/>
</LinearLayout>


styles.xml

<style name="SwitchCustom">
<item name="android:gravity">center_vertical</item>
<item name="android:thumb">@drawable/switch_selector</item>
<item name="android:track">@drawable/shape_switch_track</item>
<item name="android:textOn">ON</item>
<item name="android:textOff">OFF</item>
<item name="android:textStyle">bold</item>
<item name="android:showText">true</item> <!--textOff ,textOn 지정한 글자를 보여준다. -->
</style>


switch_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_switch_on" android:state_checked="true" android:state_pressed="true" />
<item android:drawable="@drawable/shape_switch_on" android:state_checked="true" android:state_focused="false" />
<item android:drawable="@drawable/shap_switch_off" android:state_checked="false" android:state_pressed="true" />
<item android:drawable="@drawable/shap_switch_off" android:state_checked="false" android:state_focused="false" />
</selector>



shop_switch_on.xml (ON일때)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/cm_on_bt"/>
<size android:width="55dip" android:height="35dip"></size>
</shape>


preview



shap_switch_off.xml (OFF일때)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/cm_off_bt"/>
<size android:width="55dip" android:height="35dip"></size>
</shape>


preview



shape_switch_track.xml  (배경색 지정)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/white"/>
<size android:width="55dip" android:height="35dip"></size>
</shape>


preview