是一种不好的做法,在 MVVM 应用的 XML 布局中公开活动



一般的想法是XML布局对ViewModel的引用,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout">
    <data>
        <variable
            name="aboutViewModel"
            type="com.app.about.AboutActivity" />
    </data>

问题是,如果是一个不好的做法,也会暴露这样的活动:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout">
    <data>
        <variable
            name="aboutActivity"
            type="com.app.about.AboutActivity" />
    </data>

因为有时我只需要调用函数来打开或关闭活动,我认为这些不足以成为创建新的 ViewModel 的理由。

谢谢

如果您遵循OOB - 关注点分离,那么您不应该将VMActivity紧密耦合。此外,您不必创建新VM或紧密耦合当前VM,您只需像这样访问活动/上下文:

android:onClick="@{(view)->((Activity)(view.getContext()))}"

最新更新