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
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)}">