android控件-Switch使用

1、佈局代碼

<Switch
        android:id="@+id/switchs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/width_15"
        android:showText="false"
        android:switchMinWidth="@dimen/width_41"
        android:thumb="@drawable/switch_thumb"
        android:track="@drawable/switchs_bg"
        app:layout_constraintBottom_toBottomOf="@id/defaultAddressText"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/defaultAddressText" />

2、添加開關按鈕的圓點背景switch_thumb

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

3、添加開關按鈕圓點選中的背景色switch_thumb_select

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/white" />
    <stroke android:color="@color/color_E5E5E5"
        android:width="@dimen/width_1"/>
    <size
        android:width="@dimen/width_25"
        android:height="@dimen/width_25" />
</shape>

4、添加開關按鈕圓點未選中的背景色sswitch_thumb_unselect

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/white" />
    <stroke android:color="@color/color_E5E5E5"
        android:width="@dimen/width_1"/>
    <size
        android:width="@dimen/width_25"
        android:height="@dimen/width_25" />
</shape>

5、添加開關按鈕的背景switchs_bg

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switchs_on" android:state_checked="true" />
    <item android:drawable="@drawable/switchs_off"  android:state_checked="false"/>
</selector>

6、添加開關按鈕的選中背景switchs_on

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/color_4CD964" />
    <corners android:radius="@dimen/width_23" />
    <stroke android:color="@color/color_E5E5E5"
        android:width="@dimen/width_1"/>
    <size android:height="@dimen/width_25" />
</shape>

7、添加開關按鈕的未選中背景switchs_off

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
    <corners android:radius="@dimen/width_23" />
    <stroke
        android:width="@dimen/width_1"
        android:color="@color/color_E5E5E5" />
    <size android:height="@dimen/width_25" />
</shape>

 

8、最後在代碼中選擇未選中的使用方式

// 默認選中狀態 false爲未選中 true爲選中
switchs.setChecked(true);
// 開關按鈕的點擊事件
switchs.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //選中
            } else {
            }
        });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章