android - 在 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 处理数据
我在这种方法中看到的问题是,如果视图被替换,现在视图中的逻辑必须被替换,它不像它应该的那样“愚蠢”。
处理这种情况的首选方法是什么?
解决方案
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
推荐阅读
- r - optim() 得到观察到的信息矩阵
- ajax - 如何使用一个触发器在多个屏幕上显示内容?
- python - 使用 utf-8 编码和解码返回 UnicodeError
- linux - 在 Linux 下为 Go Lang 编译 MuPdf
- python - 在不和谐机器人中未定义踢
- python - RGB像素的熵
- tensorrt - 使用 TensorRT 进行自定义对象检测
- android - 如何从 Cloud Firestore android 中的父集合中获取集合和子集合
- azure - Azure-cli 删除所有 VM 和磁盘以及资源组下的所有内容
- windows - 如何批量删除行数中的标题