MVVM体系结构中单击事件的位置

时间:2018-08-09 13:13:23

标签: android mvvm data-binding android-databinding

我正在尝试将MVVM与数据绑定一起使用。在哪里应该编写click事件(Viewmodel或Activity)

欢迎示例...

1 个答案:

答案 0 :(得分:0)

您可以在其中任一事件上编写点击事件。就个人而言,我的偏好取决于我想要实现的目标以及实现它所需要的目标。

  

ViewModel中的点击事件

定义您的ViewModel。通过回调与您的活动进行交流。

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();
    }
}

在您的活动中实施此回调:

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

将ViewModel作为变量传递给XML。然后执行以下操作:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/button_background"
    android:layout_margin="20dp"
    tools="CLICK ME!!!"
    android:textColor="@android:color/white"
    android:onClick="@{() -> ViewModel.doOnClick(ViewModel.callback)}"/>
  

活动中的点击事件

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

然后使用您的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}"/>

有关更多信息,请查看官方文档here