如何解决自定义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>
这就是我想要的
解决方法
我认为您应该使用滑动标签布局而不是switchcompat来满足您的要求。我发现了一个第三方库,它看起来像您想要的一样。
Click Here to Use This Library
,您可以实现以下目标:
使用标准 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
包裹在一个容器(LinearLayout
,CardView
....)中,并用笔触填充一下。
如果您希望按钮的两边都带有圆角,可以检查类似this question的内容。
,我通过使用自定义向量(里面的文本是一个掩码)来实现设计,它替代了开关的状态指示器。然后我使用自定义边框设计更改了 switch compat 背景矢量以实现边框。我很快会再次更新这个答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。