Muhamed Raafat
Muhamed Raafat

Reputation: 277

where to put click listeners in mvvm android

I am trying to follow MVVM design pattern in my android projects, but I faced some problems:
1. I don't know where to put click listeners, put it into the ViewModel or into the view if the action is to transport to another activity/fragment or doing some logic without redirecting to another view
2. I knew that shared preference will be put into the model but create a separate class to all shared preference only or put it into the model class example: in login, I want to save username & password does I make my shared preference functions in UserModel or make a new class and name it SharedPreference ??

Thanks in advance.

Upvotes: 16

Views: 8986

Answers (3)

Subham Naik
Subham Naik

Reputation: 421

   <Button
       android:id="@+id/btn_nw"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="@{() -> viewModel.testLoginModuleClicked()}"
       android:text="Login"/>

In ViewModel class

val loginClickEvent = SingleLiveEvent<Void>()
fun testLoginModuleClicked() {
    loginClickEvent.call()
}

in your activity/fragment class

 loginVM.loginClickEvent.observe(this, Observer {
        callMockApi()
    })

Upvotes: 5

Harrison Tiu
Harrison Tiu

Reputation: 336

  1. Put the on click listeners in your activity/fragment and not in the view-model as listeners are still part of the view.

  2. Shared preference methods should not be called inside the view-model itself, instead, make your view-model call a class that would do the saving of information into the shared preference. In this case, I would recommend using repository pattern. Your view-model will now then call method x() from your repository, and method x() will now then do the saving of information through shared preference, local database or maybe through the cloud.

Upvotes: 25

Dinesh Raj
Dinesh Raj

Reputation: 654

  <LinearLayout
      android:id="@+id/item_people"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:clickable="true"
      android:orientation="vertical"
      android:onClick="@{stateViewModel::onItemClick}">

  </LinearLayout>

in viewmodel

 public void onItemClick(View v){

    }

by creating function in view mode you can add click listener.

Next for shared preferenece , create utils file in common.so that you can use it for entire app.

Upvotes: 0

Related Questions