0

Im trying to learn view models and implement them in my app. I have been following a tutorial on getting me started but, I have a couple questions.

  1. How do i listen for a button click? Since all the business logic is suppose to be stored in the view model would I put an OnClick listener there? Or would i put it with my onChange method in the activity that launches the fragment?

  2. How to tell the fragment to use the view model?

Update was looking at this guys tutorial Location of click event in MVVM architecture . Isn't the whole point of mvvm to eliminate the need of interfaces?

Update 2: Found where you can use data binding to shove OnClick listener into button here: Handle onClick event with Databinding and MVVM and Using DataBinding library for binding events

Live data observe code from activity launching fragment

 //private BattleRhythmViewModel battleModel;
   battleModel = ViewModelProviders.of(this).get(BattleRhythmViewModel.class);

   battleModel.getEvents().observe(this, new Observer<ArrayList<Event>>() {
       @Override
       public void onChanged(@Nullable ArrayList<Event> events) {
        // Add newly created events to array/recycler view
           // Another one for pushing new platform/content to database


       }
   });
}

View model for fragment

public class BattleRhythmViewModel extends ViewModel {

private MutableLiveData<ArrayList<Event>> battleRhythmEvents;
private MutableLiveData<ArrayList<TableData>> battleRhythmExtra;

public LiveData<ArrayList<Event>> getEvents()
{
    return battleRhythmEvents;
}

public LiveData<ArrayList<TableData>> getExtras()
{
    return battleRhythmExtra;
}


}
Rob
  • 133
  • 3
  • 16

0 Answers0