如何使用SavedStateHandle和导航安全Args [英] How to use SavedStateHandle and navigation Safe Args

查看:279
本文介绍了如何使用SavedStateHandle和导航安全Args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个选项可以在片段之间传递数据,即导航的安全args和viewModel的SavedStateHandle,它们之间有什么区别以及如何在正确的位置使用它们?

I have two options to pass data between fragment, the navigation's safe args and viewModel's SavedStateHandle, what's the difference between them and how to use them in the correct place?

推荐答案

如果您使用hilt,则可以像这样将进入的参数包装在片段(和其他组件)中

If you are using hilt you can wrap the incoming arguments in the fragment (and other components) like so

open class BaseFragment : Fragment() { // Inherit your fragment from this

    override fun setArguments(args: Bundle?) {
        if (args != null) {
            super.setArguments(Bundle(args).apply {
                putBundle(BUNDLE_ARGS, args) // Wrap the arguments as BUNDLE_ARGS
            })
        } else {
            super.setArguments(null)
        }
    }
}

然后对于视图模型,您可以从类似的东西继承

and then for the view model, you can inherit from something like that

open class ArgsViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {

    val arguments get() = savedStateHandle.get<Bundle>(BUNDLE_ARGS)

    @MainThread
    inline fun <reified Args : NavArgs> navArgs() = NavArgsLazy(Args::class) {
        arguments ?: throw IllegalStateException("ViewModel $this has null arguments")
    }
}

然后像使用安全参数一样使用它

And then use it just like you would use safe args

class FooViewModel @ViewModelInject constructor(
    @Assisted savedStateHandle: SavedStateHandle
) : ArgsViewModel(savedStateHandle) {

    private val args: FooFragmentArgs by navArgs()
}

这篇关于如何使用SavedStateHandle和导航安全Args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆