cesards
2/24/2015 - 11:59 AM

Simple setup for item backgrounds pre - post lollipop

<?xml version="1.0" encoding="utf-8"?>
<!-- res/values/themes.xml -->

<resources>
    <style name="Default" parent="Theme.AppCompat.Light">
        <item name="selectableItemBackground">@drawable/my_ripple</item>
        <item name="android:selectableItemBackground">@drawable/my_ripple</item>
        <!-- for the following two, you shoud use a different ripple without mask -->
        <item name="selectableItemBackgroundBorderless">@drawable/my_ripple</item>
        <item name="android:selectableItemBackgroundBorderless">@drawable/my_ripple</item>
    </style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/my_ripple.xml -->

<!-- This will be the drawable used on API < 21 -->
<!-- Obviously you can specify here whateer you want -->
<!-- like activated states, animated states, shapes, pngs, whatever like any other drawable-->
<!-- I've just put 2 states (pressed,focused) using the same color than the v21 ripple -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/my_color_highlight_focus" android:state_focused="true"/>
    <item android:drawable="@color/my_color_highlight_press" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable-v21/my_ripple.xml -->

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/my_color_highlight">
    <!-- The Mask can be a shape drawable if you want -->
    <!-- Also removing the mask makes the ripple "borderless" -->
    <!-- here we're using just any color to have a rectangular limit for the ripple -->
    <item android:id="@android:id/mask"
          android:drawable="@color/my_color_highlight" />
</ripple>
<?xml version="1.0" encoding="utf-8"?>

<!-- res/values/colors.xml -->
<resources>
    <!-- main color for drawable-v21/my_ripple -->
    <color name="my_color_highlight">#FFE99E63</color>
    <!-- main color for drawable/my_ripple -->
    <color name="my_color_highlight_press">#77E99E63</color>
    <color name="my_color_highlight_focus">#CCE99E63</color>
</resources>
AppCompat-v7:21 provides a very useful way of dealing with pressed/focused/activated states maintaining backwards compatibility downto API-7, but there's a small issue (big for some) with the default selectableItemBackground: It uses some PNGs and/or default values for API<21.

The main reason is that android drawable resource definitions (prior API 21) CANNOT use theme attributes at all, so there's no way of making something like:
<shape android:shape="rectangle">
        <solid android:color="?attr/colorControlHighlight" />
</shape>

For this, I've put this simple mockup on how to give your app better drawables that the appcompat defaults.