首页 > 解决方案 > 自定义 Android SwitchCompat

问题描述

在我的 Android 应用程序中,我有一个SwitchCompat用于过滤列表数据的列表。默认主题不能满足我的目的,我需要的是一个类似 iOS 的开关。我不知道如何自定义它以使其看起来与 iOS 开关完全一样。谢谢阅读。

            <androidx.appcompat.widget.SwitchCompat
                android:id="@+id/switch_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@xml/custom_switch_background_main"
                android:theme="@style/AppTheme.SwitchOverlay"/>

当前主题 梦想主题

这是我目前存档的

在此处输入图像描述

custom_switch_background_main.xml

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

custom_switch_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="50dp" />
    <solid android:color="@color/transparent" />
    <stroke
        android:width="1dp"
        android:color="@color/hello" />
</shape>

这就是我要的

在此处输入图像描述

标签: androidandroid-layoutandroid-buttonmaterial-components-androidandroid-switch

解决方案


我认为您应该使用滑动选项卡布局而不是 switchcompat 来满足您的要求。我找到了一个第三方库,它看起来像你想要的一样的开关。

您可以根据需要自定义颜色和圆角半径。

单击此处使用此库


推荐阅读