首页 > 解决方案 > 在 Activity 和 ViewModel 之间传递数据

问题描述

我正在学习用于 Android 编程的新架构组件,我很难理解活动的职责是什么。我知道他们只应该处理 UI,这是有道理的,但在多大程度上呢?假设我有一个活动,最初有一个 EditText,用户可以在其中输入一个字符串。在此下方有一个按钮,可添加另一个 EditText 供用户输入另一个字符串。应该如何在幕后处理这些数据?我提出的两个解决方案如下:

1) 处理 ViewModel 中的数据。

用户单击按钮 -> Activity 告诉 ViewModel -> ViewModel 维护 EditTexts 列表 -> 用户完成后,Activity 告诉 ViewModel -> ViewModel 处理数据

我用这种方法看到的问题是,现在 ViewModel 中有 UI 元素,我必须处理某种状态(用户添加了一些 EditText,但随后取消了整个操作,ViewModel 必须清除它的列表)

2)处理Activity中的数据。

用户单击按钮 -> Activity 维护 EditTexts 列表 -> 用户完成后,Activity 将字符串列表发送到 ViewModel -> ViewModel 处理数据

我在这种方法中看到的问题是,如果视图被替换,现在视图中的逻辑必须被替换,它不像它应该的那样“愚蠢”。

处理这种情况的首选方法是什么?

标签: androidmvvm

解决方案


First of a ViewModel should never include a View such as EditText, as quouted from the ViewModel page: "Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.". When you do, it might cause a memory-leak so that excludes option 1.

Secondly the ViewModel shouldn't be used for processing data, it is merely a container for the data. Processing should be preformed in the background and the result should be stored in the ViewModel, so that potential listeners can react to the data-change.

So to answer you question: In this case I would create a custom ListView with a custom view that contains a EditText. Our ViewModel will contain MutableLiveData for a String list called entries, like this MutableLiveData<List<String>> entries = new MutableLiveData<List<String>>(); which we can set by calling the setValue(object) method.

When the user pushes the button all the text from the EditText views are combined in a String list and we set entries to the created list with the setValue(object) method. All the listeners to entries, will be providen with the new data. So for example you could kick off a background job for processing the new values, like so: model.entries.observe(this, Observer { ProcessStringListTask().execute(it) }) (note that the code is in Kotlin).

Hopes this answers your question.

Best regards,

Dingenis


推荐阅读