I'm trying to use MVVM with databinding .. Where should I write click event (Viewmodel Or Activity)
Examples are welcome...
You can write your click events on either. Personally, my preference depends on what I want to achieve and what I need to achieve it.
Click event in ViewModel
Define your ViewModel. Communicate with your activity via a Callback.
public class MyViewModel extends ViewModel{
private MyCustomCallback callback;
...
public void doOnClick(MyCustomCallback mCallback){
boolean isSuccessful = doMyAction.execute();
if (isSuccessful){
mCallback.actionIsSuccessful();
} else {
mCallback.actionFailed();
}
}
...
public void setCallback(callback){
this.callback = callback;
}
public MyCustomCallback getCallback(){
return this.callback;
}
...
public interface MyCustomCallback{
void actionIsSuccessful();
void actionFailed();
}
}
Implement this callback in your activity:
public class MyActivity extends AppCompatActivity{
...
private MyCustomCallback callback;
@Override
protected void onCreate(Bundle savedInstanceState){
...
callback = new MyViewModel.MyCustomCallback{
@Override
public void actionIsSuccessful(){
//do something when action is successful
}
@Override
public void actionFailed(){
//do something when action fails
}
}
viewModel.setCallback(callback);
}
}
Pass your ViewModel as a variable to your XML. Then do this:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button_background"
android:layout_margin="20dp"
tools:text="CLICK ME!!!"
android:textColor="@android:color/white"
android:onClick="@{() -> ViewModel.doOnClick(ViewModel.callback)}"/>
Click events in Activity
public class MyActivity extends AppCompatActivity{
...
private MyCustomCallback callback;
@Override
protected void onCreate(Bundle savedInstanceState){
//initialize your binding
...
binding.setClickHandler(new MyActivityClickHandler());
}
public class MyActivityClickHandler{
public void onClickMeClicked(View view){
//do something
}
}
}
Then in your XML:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button_background"
android:layout_margin="20dp"
android:text="@string/verify"
android:textColor="@android:color/white"
android:onClick="@{ClickHandler::onClickMeClicked}"/>
For more information check the official doc here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With