ir2pid
ir2pid

Reputation: 6126

Android how to handle recyclerview clicks in mvvm architecture

I want to handle clicks in my recyclerview rows and currently pass my presenter to my viewholder bindings.

Presenter interface:

interface IMainPresenter{
  public void showDetail(Pojo pojo);
}

Viewholder:

class ViewHolder(itemView: View, val parent: ViewGroup?, private val binding: ListMainBinding) : RecyclerView.ViewHolder(itemView) {
            fun bind(pojo: Pojo, mainPresenter: IMainPresenter) {
                binding.pojo = pojo
                binding.mainPresenter = mainPresenter
                binding.executePendingBindings()
            }
        }

and in my layout I call a method of my presenter on the onClick attribute

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <import type="android.view.View" />

        <variable
            name="mainPresenter"
            type="com.noisyninja.androidlistpoc.views.main.IMainPresenter" />

        <variable
            name="pojo"
            type="com.noisyninja.androidlistpoc.model.Pojo" />
    </data>

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/black"
            android:onClick="@{(view) -> mainPresenter.showDetail(pojo)}"
            ...
            ...
            ...

I think passing the presenter is not a good design, but what is a better approach to handle clicks from rows which trigger a method in my presenter?

Upvotes: 3

Views: 1934

Answers (1)

atarasenko
atarasenko

Reputation: 1808

IMHO a better approach would be to add OnItemClickListener to RecyclerView like here, and call

ItemClickSupport.addTo(recyclerView).setOnItemClickListener{
        recycler, position, v -> 
        mainPresenter.showDetail(recycler.getAdapter().getItem(position))
}

during the setup of RecyclerView.

Upvotes: 1

Related Questions