Tag Archives: custom highlight

(Android) Custom list item highlight

Here’s a simple and direct approach to customizing the background of a selected item in a listview:

First, in your list item layout add android:background="?android:attr/activatedBackgroundIndicator to your parent view. For example:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/drawer_item_height"
    android:orientation="horizontal"
    android:paddingRight="@dimen/default_gap"
    android:paddingLeft="@dimen/default_gap"
    android:gravity="center_vertical"
    android:longClickable="false"
    android:background="?android:attr/activatedBackgroundIndicator">
   
    <!-- View children here-->

</RelativeLayout>

Next, override the activeBackgroundIndicator style in your theme. i.e:


<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:activatedBackgroundIndicator">@drawable/activated_background</item>
</style>

You’ll notice we’re indicated a custom drawable to use: activated_background. Go ahead and create that in your drawable directory. It should look like this:


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@color/row_activated" />
    <item android:state_focused="true" android:drawable="@color/row_activated" />
    <item android:state_pressed="true" android:drawable="@color/row_activated" />
    <item android:state_checked="true" android:drawable="@color/row_activated" />
    <item android:drawable="@android:color/transparent" />
</selector>

Obviously you can customize it further by setting different colors depending on the state. @color/row_activated is just a color that was defined in colors.xml: <color name="row_activated">#7986CB</color>.