Best practice for Android MVVM startActivity

前端 未结 6 1243
你的背包
你的背包 2021-01-30 13:16

I am building an Android App using MVVM and DataBinding. And I have a function inside my ViewModel that starts an Activity. Is it okay to have an onClick call inside a ViewModel

6条回答
  •  生来不讨喜
    2021-01-30 13:30

    As the principle of MVVM points out that only View (activity/fragment) holds reference to the ViewModel and the ViewModel shouldn't hold reference to any View.

    In your case, to start an activity, I will do like this:

    MyViewModel.class

    public class MyViewModel {
    public static final int START_SOME_ACTIVITY = 123;
    
     @Bindable
     private int messageId;
    
     public void onClick() {
      messageId = START_SOME_ACTIVITY;
      notifyPropertyChanged(BR.messageId); //BR class is automatically generated when you rebuild the project
     }
    
     public int getMessageId() {
            return messageId;
     }
    
     public void setMessageId(int message) {
            this.messageId = messageId;
     }
    
    }
    

    And in your MainActivity.class

    @BindingAdapter({"showMessage"})
    public static void runMe(View view, int messageId) {
        if (messageId == Consts.START_SOME_ACTIVITY) {      
            view.getContext().startActivity(new Intent(view.getContext(), SomeActivity.class));      
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        finish(); //only call if you want to clear this activity after go to other activity
    }
    

    finally, in your activity_main.xml

提交回复
热议问题