在 MVVM 应用程序的 XML 布局中公开 Activity 是一种不好的做法吗?
is a bad practice expose the Activity in the XML layout in a MVVM app?
总体思路是 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>
问题是,如果这是一个糟糕的做法,也会像这样暴露 activity:
<?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>
因为有时我只需要打开或关闭 activity 的调用函数,我认为这些不足以成为创建新 ViewModel 的理由。
谢谢
如果您遵循 OOB - 关注点分离,那么您不应将 VM
与 Activity
紧密结合。此外,您不必创建新的 VM
或紧密耦合当前的 VM
,您可以像这样访问 activity/context:
android:onClick="@{(view)->((Activity)(view.getContext()))}"
总体思路是 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>
问题是,如果这是一个糟糕的做法,也会像这样暴露 activity:
<?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>
因为有时我只需要打开或关闭 activity 的调用函数,我认为这些不足以成为创建新 ViewModel 的理由。
谢谢
如果您遵循 OOB - 关注点分离,那么您不应将 VM
与 Activity
紧密结合。此外,您不必创建新的 VM
或紧密耦合当前的 VM
,您可以像这样访问 activity/context:
android:onClick="@{(view)->((Activity)(view.getContext()))}"