簡體   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