switch_track_selector.xml

위에가 off 상태 아래가 on 상태

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

    <item
        android:drawable="@drawable/switch_track_on"
        android:state_checked="true"/>

</selector>

switch_track_on.xml

on일때 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius= "30dp" />

<size
    android:width="26dp"
    android:height="21dp" />

<solid android:color="#4F77E7" />
</shape>

switch_track_off.xml

off일때 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius= "30dp" />

<size
    android:width="26dp"
    android:height="21dp" />

<solid android:color="#E9ECEF" />
</shape>

layout에서 switch

<Switch
    android:id="@+id/navi_save_ck"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dp"
    android:checked="true"
    android:layout_gravity="center"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_track_selector"
    app:switchMinWidth="51dp">

</Switch>

이쁨

아이템 사용

binding.navView.findViewById<Switch>(R.id.navi_save_ck).isChecked = viewModel.fun()
binding.navView.findViewById<Switch>(R.id.navi_save_ck).setOnCheckedChangeListener { _, b ->
    viewModel.fun()
}

원래 체크박스로 사용하던 기능을 스위치로 변경하여 만들었다.

사이즈 랑 옵션 잘사용하시길 

tmi -소요시간 2시간 (이쁘게 만들라고)

+ Recent posts