Be OnClickListener and OnLongClickListener in ViewModel or Fragment?

446 Views Asked by At

Be onClickListener and onLongClickListener for recyclerView items in ViewModel or Fragment? Why?

First one get onClickListener from viewModel:

class MyFragment : Fragment() {
...
  private fun setUpAdapter() = MyAdapter({ todoEntity, todoTitle ->
    viewModel.onClickListener(todoEntity, todoTitle)
   }, { todoEntity: TodoEntity ->
     viewModel.onTodoLongClick(todoEntity)
  })
...
}

Second one get onClickListener in Fragment:

class MyFragment : Fragment() {
...
  private fun setUpAdapter() = MyAdapter({ todoEntity, todoTitle ->
    onClickListener(todoEntity, todoTitle)
   }, { todoEntity: TodoEntity ->
     onTodoLongClick(todoEntity)
  })

 fun onClickListener(todoEntity: TodoEntity, todoTitle: TextView) {
   // Do Something
 }

 fun onTodoLongClick(todoEntity: TodoEntity) {
   // Do Something
 }

...
}

Which one is better?

2

There are 2 best solutions below

2
Michiel On

In the view, the fragment. The ViewModel should have no knowledge whatsoever from the View, so common practive would be:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val button = view.findViewById<Button>(R.id.button)
    button.setOnClickListener { viewModel.doStuff() }
}

The listener is set in the view, but the actual code lives in the viewmodel. The fragment should be as small as possible and only connects the layout and its' lifecycle with the behaviour in the ViewModel.

0
NhatVM On

For item of recyclerview, you should create a callback.

In the fragment, you init adapter for recyvlerview and you also init a callback and pass it to the adapter.

If you are using databinding for item of adapter, you can bind this callback.

When there is a event (click or long click), callback to fragment, fragment will calls viewmodel to process.

It is better to check my example:

https://github.com/frank-nhatvm/stackoverflowapp/blob/master/app/src/main/java/com/frank/stackoverflowapp/pages/question/listquestions/adapters/QuestionsAdapter.kt