繁体   English   中英

自定义 Android SwitchCompat

[英]Customise Android SwitchCompat

在我的 Android 应用程序中,我有一个带有SwitchCompat的列表来过滤列表数据。 默认主题不能满足我的目的,我需要的是类似 iOS 的 switch。 我不知道如何自定义它以使其看起来与 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>

这就是我要的

在此处输入图片说明

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

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

单击此处使用此库

您可以实现以下目标:

在此处输入图片说明

使用标准MaterialButtonToggleGroup

      <com.google.android.material.button.MaterialButtonToggleGroup
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:selectionRequired="true"
           app:singleSelection="true">
           
           <com.google.android.material.button.MaterialButton
               app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.rounded"
               style="?attr/materialButtonOutlinedStyle"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="ITEM1"/>

           <com.google.android.material.button.MaterialButton
               app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.rounded"
               style="?attr/materialButtonOutlinedStyle"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="ITEM2"/>
           
           
       </com.google.android.material.button.MaterialButtonToggleGroup>

和:

<style name="ShapeAppearanceOverlay.App.rounded" parent="">
    <item name="cornerSize">50%</item>
</style>

如果你想要边框,你可以将MaterialButtonToggleGroup包裹在一个容器( LinearLayoutCardView ....)中,应用一个小填充。

如果你想要两边都有圆角的按钮,你可以检查这样的问题

我通过使用自定义向量(里面的文本是一个掩码)来实现设计,它替代了开关的状态指示器。 然后我使用自定义边框设计更改了 switch compat 背景矢量以实现边框。 我很快会再次更新这个答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM