Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android selectableItemBackground selection

i want to change background of my view when the state is "activated" and i want to preserve the effects(ripple) of ?attr:selectableItemBackground. Is it possible to extend or combine selector of ?attr:selectableItemBackground?

like image 844
Asiat Avatar asked Feb 10 '16 09:02

Asiat


2 Answers

You can use a LayerDrawable in order to draw the ripple effect drawable (?attr:selectableItemBackground) over your activated state color.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <selector>
            <item android:state_activated="true">
                <color android:color="?attr/colorPrimary"/>
            </item>
            <item>
                <color android:color="@android:color/transparent"/>
            </item>
        </selector>
    </item>
    <item android:drawable="?attr/selectableItemBackground"/>
</layer-list>

Edit: As it's not possible to use theme attributes in an XML drawable before API 21, it seems to be better to put the ripple effect drawable as a foreground drawable, and the activated color selector drawable as a background drawable.

<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/yourView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground"
    android:background="@drawable/activated_color_selector">

With res/drawable/activated_color_selector.xml containing:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true">
        <!-- Can't use the ?attr/colorPrimary before API 21 -->
        <color android:color="@color/primaryColor"/>
    </item>
    <item>
        <color android:color="@android:color/transparent"/>
    </item>
</selector>
like image 178
Nit Avatar answered Nov 10 '22 01:11

Nit


For those who only care about API >= 21 now in 2020, here's a simpler solution :

<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) If you don't override colorControlHighlight in your theme, the ripple's color will be Android's default. If you do override it in your theme but want to use Android's default for a specific case use ?android:colorControlHighlight instead.

like image 2
flawyte Avatar answered Nov 10 '22 00:11

flawyte