Gives visual feedback when an item is pressed.
Start with an xml file to define a selector drawable. Right-click on res->New->Android Resource File, Resource type: Drawable, Root element: selector, then 'OK'. We've named this file 'list_item_selector.xml':
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/colorPrimaryLight" android:state_pressed="true" /> // Add all these states to cover the various selection possibilities <item android:drawable="@color/colorPrimaryLight" android:state_activated="true" /> <item android:drawable="@color/colorPrimaryLight" android:state_selected="true" /> <!-- This should have a default drawable color = "@android:color/background_light" --> // Default unselected state <item android:drawable="@android:color/background_light" /> </selector>In the example of a list item in a RecyclerView, go to the xml layout file for the list item and add the following to the root layout:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/list_item_selector "> // Add the selector xml file as the background ... </LinearLayout>
