Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewModel and click listeners

Coming from MVP to viewModels, I feel I'm a bit lost when it comes to where to place some code. One example is where to place the click listeners. in MVP I would do something like this

myButton.setOnClickListener { presenter.onMyButtonClicked }

should I be doing the same with a ViewModel? I don't think so. because it means that I'm treating the viewmodel as if it was a presenter.

But, on the other hand, if I handle the click listener in the view (activity or fragment), the view might not end up as dumb as it should be.

Where is the most suitable place in which a click listener should be handled?

like image 671
a fair player Avatar asked Jul 12 '20 17:07

a fair player


1 Answers

The Best Place To add OnClick Listener is View Model when you use MVVM architecture. in MVVM architecture, with data binding, you can handle your on-click listener in many ways.

<Button
  onClick="@{()->viewModel.onMyButtonClicked()}"/>



 <Button 
      onClick="@{(view)->viewModel.onMyButtonClicked(view)}"/>

In this, No need to give Id for each. For doing this first you have to register ViewModel into your activity. in Activity onCreate you have to set the content view as I mentioned below.

ActivityMainBinding activityMainBinding = DataBindingUtils.setContentView(this,R.layout.activity_main);
activityMainBinding.viewModel = MyViewModel(application)
activityMainBinding.lifecycleOwner = this;

after this in your layout file, you have to add ViewModel variable

<layout>
    <data>
        <variable
            name="viewModel"
            type=".MyViewModel" />
    </data>
    ......
    ......
   . .....

<Button
  onClick="@{()->viewModel.onMyButtonClicked()}"/>



 <Button 
      onClick="@{(view)->viewModel.onMyButtonClicked(view)}"/>


</layout>

then If you want to do any changes in Activity, then you have to use Observable variables. that observable variable you have to observe in the activity class. based on the value you have to do the action.

like image 172
Yabaze Cool Avatar answered Oct 17 '22 05:10

Yabaze Cool