5

I'm trying to highlight a recyclerview item while adhering to MVVM principles and while using databinding. But I'm having trouble understanding how to handle selecting a row.

I currently pass my recyclerview item onclick to the viewmodel using the following interface:

public interface ItemClickListener
{
    void onItemClicked(String id);
}

The view onclick is databound:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="model"
            type="Item" />

        <variable
            name="listener"
            type="ItemClickListener" />
    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{model.name}"
        android:onClick="@{() -> listener.onItemClicked(model.name)}" />
</layout>

The viewmodel implements the interface so I have a reference to the Item. The listener is instantiated in the activity and passed into the adapter.

How would I handle selecting a recyclerview item (and giving it a background colour)? Should the viewholder implement onClickListener(View view) and pass it through my interface along with it's position?

user2929779
  • 359
  • 5
  • 13

1 Answers1

3

In an MVVM architecture, your UI is driven by the data exposed by your ViewModel. In your particular case, that means that the Item that you are displaying in your ViewHolder should be able to tell if it is selected or not. To do that, the simplest solution is to add a isSelected boolean to your Item class. That boolean will allow you to decide which backgroundColor to use in your layout.

To link everything together in an MVVM way, your ItemClickListener implementation should modify your ViewModel's List<Item> by toggling the isSelected boolean of the Item that was just clicked.

If you are using the architecture components LiveData, make sure to post the new value of the List, which I assume would notify your Adapter of the change. If you don't do it, your UI will not get refreshed since the RecyclerView will not be aware of a change in the Data being displayed.

Julien Arzul
  • 961
  • 9
  • 7