簡體   English   中英

以 selectableItemBackground 作為背景的可繪制形狀

[英]Shaped drawable with selectableItemBackground as background

我有幾個按鈕需要一個橢圓形邊框。

所以我在capsule_border.xml中有這個

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="9999dp"/>
    <stroke
        android:width="1px"
        android:color="@color/border_gray" />
</shape>

我會在需要的地方使用android:background="@drawable/capsule_border.xml

現在,我想要一個帶有橢圓形邊框的按鈕,還有一個android:background="?selectableItemBackground"用於視覺反饋。

我嘗試使用帶有 selectableItembackground 的父布局和帶有capsule_border 的按鈕。 但似乎突出顯示的可點擊區域是整個正方形。 而不僅僅是膠囊邊界內的區域。

在此處輸入圖片說明

有什么辦法可以使 selectableItemBackground 不高度覆蓋視圖的整個矩形,而只在我繪制的邊框內?

round_corners.xml

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

my_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#000000" />
            <corners android:radius="15dp" />
        </shape>
    </item>
    <item android:drawable="@drawable/round_corners" />
</ripple>

和按鈕:

<Button
    android:background="@drawable/my_ripple"
    ... />

會導致這樣:

在此處輸入圖片說明

看到這篇文章。

我有第一個答案的更簡單版本:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?colorControlHighlight"> <!-- default ripple color -->

    <item>
        <!-- the background shape when it's not being clicked -->
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
            <corners android:radius="32dp" />
        </shape>
    </item>
</ripple>

只需將其應用為背景,但如果它適用於Button請記住刪除陰影

style="?borderlessButtonStyle"

祝你好運!


在此處輸入圖片說明

這是 2020 年的一個更簡單的解決方案(API >= 21,因為我們使用的是?attr語法):

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?colorControlHighlight">
    <!-- 🡡 the ripple's color (1) -->

    <!-- 🡣 no `id` so our <shape> will be drawn and not just used as mask -->
    <item>
        <shape>
            <corners android:radius="9dp" />
            <solid android:color="@color/white" />
        </shape>
    </item>

</ripple>

(1)如果您沒有在主題中覆蓋colorControlHighlight ,波紋的顏色將是 Android 的默認顏色。 如果您確實覆蓋它但仍想使用 Android 的默認值,請改用?android:colorControlHighlight

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM