[英]Android MVVM architecture - Android references/imports in ViewModel
Based on the idea that you should not pass and Android view's or other pure Android components to ViewModel
, or have android imports there, consider the next use case: 基于您不应该将Android视图或其他纯Android组件传递给
ViewModel
或在其中导入android的想法,请考虑下一个用例:
From my Fragment
I want to launch some sort of image processing action and for that I need to initialize my object with the current xml view where I want to show the result. 从
Fragment
我想启动某种图像处理操作,为此,我需要使用当前xml视图初始化对象,并在其中显示结果。 So I create it on the ``Fragment side with the view component and then pass that object over to ViewModel
. 因此,我在``带有视图组件的片段一侧创建它,然后将该对象传递给
ViewModel
。
My problems are: 我的问题是:
I'm passing to ViewModel
an object with already reference to an Android views. 我将已经引用了Android视图的对象传递给
ViewModel
。
The logic in ViewModel
creates a Bitmap
and after processing it return that bitmap to the Fragment that observes it, as a result I have reference to some Android Bitmap libraries inside my ViewModel
ViewModel
的逻辑会创建一个Bitmap
并在对其进行处理后将该位图返回给观察它的Fragment,结果,我引用了ViewModel
一些Android位图库
How to avoid referencing Android stuff in ViewModel
if I need the work to be done there? 如果我需要在
ViewModel
中完成工作,如何避免在ViewModel
引用Android东西?
If I understood you correctly, you are inflating your views in the Fragment
, then you generate the bitmap in your ViewModel
, and then you pass it back and set it in your Fragment
, and in the process you need to pass something more to the ViewModel
than just Application
instance. 如果我对您的理解是正确的,那么您将在
Fragment
中扩展视图,然后在ViewModel
生成位图,然后将其传递回并在Fragment
设置,在此过程中,您需要将更多内容传递给ViewModel
不仅仅是Application
实例。 If that's the case you need to use the ViewModelFactory
. 如果是这种情况,则需要使用
ViewModelFactory
。 In short, you will write a small class that will create the ViewModel
for you, and then you pass it to ViewModelProviders.of(this, ...)
as a second parameter. 简而言之,您将编写一个小类,该类将为您创建
ViewModel
,然后将其作为第二个参数传递给ViewModelProviders.of(this, ...)
。
The usage is shown in this answer. 用法显示在此答案中。 If you look around you should also be able to find its usage in Google samples .
如果环顾四周,您还应该可以在Google示例中找到它的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.