简体   繁体   English

适用于Android的MVVM活动意图

[英]MVVM Activity Intent for Android

I am trying out MVVM for Android. 我正在尝试Android的MVVM。 I have a button which opens up another activity onClick. 我有一个按钮,它打开了另一个活动onClick。 Codes below: 以下代码:

View: 视图:

    <LinearLayout
            android:id="@+id/activity_test"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".mvvm.view.TestActivity">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Activity"
            android:onClick="@{viewModel.onClickButton1}"/>

    </LinearLayout>

ViewModel: ViewModel:

public View.OnClickListener onClickButton1() {
    return view -> {
        mContext.startActivity(new Intent(mContext, MockActivity.class));
    };
}

This doesn't seem to work for me. 这似乎对我不起作用。 When I click on the button, MockActivity doesn't get started. 当我单击按钮时,MockActivity无法启动。 What could be the problem? 可能是什么问题呢?

in your view file did u bind your view to your viewmodel? 您是否在视图文件中将视图绑定到视图模型?

binding.setViewModel(viewModel); binding.setViewModel(viewModel);

As a suggestion, it is better to not include view event listeners in your ViewModel but instead putting them inside the View (activity or fragment here), Then you can call the view model methods to do the work. 作为建议,最好不要在ViewModel中包括视图事件侦听器,而应将它们放在View内(此处为活动或片段),然后可以调用视图模型方法来完成工作。 The idea is, ViewModel should not have any reference to view classes at all but in your code your passing a view to the onClickButton1 method. 这个想法是,ViewModel根本不应该引用任何视图类,而是在代码onClickButton1视图传递给onClickButton1方法。

尝试使用viewModel :: onClickButton1而不是viewModel.onClickButton1

The code in your VM class should be VM类中的代码应为

public void onMyButtonClicked(View view) {
    // YOUR CODE HERE
}

And in the xml: 并在xml中:

<Button
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:onClick="@{offlineDownloadsVM::onMyButtonClicked}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM