AndroidViewModel with SavedState



我需要使用带有应用程序上下文的AndroidViewModelSavedStateHandle。我已经让它与应用程序上下文一起工作了,但我无法向它添加SavedStateHandle

这就是我所拥有的,只有应用程序上下文:

// A1. get ViewModel in Fragment
val viewModel = ViewModelProvider(viewLifecycleOwner).get(MyViewModel::class.java)
// A2. MyViewModel derives from my custom BaseAndroidViewModel
class MyViewModel(application: Application) :BaseAndroidViewModel(application)
// A3. BaseAndroidViewModel in turn derives from AndroidViewModel
open class BaseAndroidViewModel(application: Application) : AndroidViewModel(application)

我认为对于这个问题,这可能会被简化为:

// B1. get ViewModel in Fragment
val viewModel = ViewModelProvider(viewLifecycleOwner).get(MyViewModel::class.java)
// B2. BaseAndroidViewModel in turn derives from AndroidViewModel
class MyViewModel(application: Application) : AndroidViewModel(application) 

那么,对于在MyViewModel中也有SavedStateHandle,我必须如何修改片段中的调用(示例代码中的B1行(?我需要给工厂SavedStateViewModelFactory打一个明确的电话吗?那会是什么样子?(我还是Kotlin/Android的新手,我以前从未在工厂工作过(

EDIT:AndroidX-Activity 1.2.0AndroidX-Fragment 1.1.0的最终版本中,他们将SavedStateViewModelFactory作为AppCompatActivity/FFragment中的默认工厂,因此不需要覆盖默认工厂(这就是本答案的后半部分所做的(

更新然后使用

class MyViewModel(val savedStateHandle: SavedStateHandle): ViewModel()
class MyAndroidViewModel(application: Application, val savedStateHandle: SavedStateHandle): AndroidViewModel(application)

应该只是工作。


原件:

我必须如何修改片段中的调用(示例代码中的B1行(?是否需要显式调用工厂SavedStateViewModelFactory?那会是什么样子?

在AndroidX活动1.2.0中,他们添加了一个名为getDefaultViewModelProviderFactory():的新方法

+    @NonNull
+    @Override
+    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
+        if (getApplication() == null) {
+            throw new IllegalStateException("Your activity is not yet attached to the "
+                    + "Application instance. You can't request ViewModel before onCreate call.");
+        }
+        return ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());
+    }
+

这意味着如果我有BaseActivityBaseFragment,我可以将其从viewmodel-savedstate:换成SavedStateViewModelFactory

class BaseActivity: AppCompatActivity() {
override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory = 
SavedStateViewModelFactory(application, this, intent?.extras ?: Bundle())
}
class BaseFragment: Fragment() {
override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory = 
SavedStateViewModelFactory(requireActivity().application, this, arguments ?: Bundle())
}

一旦你有了它,你就可以依赖ViewModel的自动实例化,SavedStateHandle作为它们的参数之一:

class MyViewModel(val savedStateHandle: SavedStateHandle): ViewModel()
class MyAndroidViewModel(application: Application, val savedStateHandle: SavedStateHandle): AndroidViewModel(application)

注意订单application, savedStateHandleSavedStateViewModelFactory所期望的。

但是,如果您确实需要自定义参数,那么在调用ViewModelProvider(viewModelStoreOwner).get(...)方法时必须提供object: AbstractSavedStateViewModelFactory

相关内容

  • 没有找到相关文章

最新更新