Best practice for Android MVVM startActivity

前端 未结 6 1252
你的背包
你的背包 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:53

    As per the data binding documentation. There are 2 ways to do that:

    1- MethodReferences : You have to pass the view as a parameter to the function, or you will get a compile time error.
    If you will use this way do a separate class as example here that handle such events.

    MyHandler

    public class MyHandler {
       public void onClick(View view, long productId) {
            Context context = view.getContext();
            Intent intent = new Intent(context, ProductDetailActivity.class);
            intent.putExtra("productId", productId);
            context.startActivity(intent);
        }
    }
    

    XML

    
            
    
        android:onClick="@{myHandler.onClick(viewModel.product.id)}">
    

    2- Listener bindings : You don't need to pass the view as the example here.
    But if you want to startActivity make your viewModel extends AndroidViewModel and you will use the applicaion object.

    ViewModel

    public class MyViewModel extends AndroidViewModel {
        public void onClick(long productId) {
            Intent intent = new Intent(getApplication(), ProductDetailActivity.class);
            intent.putExtra("productId", productId);
            context.startActivity(intent);
        }
    }
    

    XML

    android:onClick="@{() -> viewModel.onClick(viewModel.product.id)}">
    

提交回复
热议问题