Touch selector

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>

ItemTouchHelper

Add an ItemTouchHelper to recognize when a user swipes to e.g. delete an item. An ItemTouchHelper enables touch behaviour (like swipe and move) on each ViewHolder, and uses callbacks to signal when a user is performing these actions:

Create a Contract class:

new ItemTouchHelper (new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { // Detects side swipes
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false; // Do nothing if the user tries to 'move' the object
            }

            // Called when a user swipes left or right on a ViewHolder
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                // Here is where you'll implement swipe to delete
            }
        }).attachToRecyclerView(mRecyclerView); // Attach to the relevant View

ud851-Exercises-student\Lesson09-ToDo-List\T09.01