如何在FragmentActivity的onBackPressed事件中传递数据或添加观察者

问题描述 投票:0回答:1

我正在开发android应用,当用户按下后退按钮(这意味着触发了onBackPress事件)时,我面临传递数据的问题。我想用viewmodel触发观察者事件,但是它不起作用。这样。

// First Fragment
private val viewModel: MyViewModel by bindViewModel()
viewModel.currencyVal.observe { state ->
    Timber.i("Event fired")
}
    ...

// Second fragment which was displayed with fragment transaction. This code is when user pressed back button. like override fun onBackPressed
private val viewModel: MyViewModel by bindViewModel()
viewModel.currencyVal(5)

// MyViewModel
    ...
val currencyVal = MutableLiveData<Int>()
    ...
fun setCurrencyVal(currencyVal: Int) {
    currencyVal.value = currencyVal
}

这里是bindViewModel函数

protected inline fun <reified T : ViewModel> bindViewModel(
    crossinline initializer: T.() -> Unit = {}
): Lazy<T> = nonConcurrentLazy {
    ViewModelProviders.of(requireActivity())
        .get(T::class.java)
        .also { it.initializer() }
}

并且也无法通过片段事务传递数据。

有人可以建议用户在FragmentActivity中按下后退按钮时如何传递数据吗?

谢谢。

android kotlin mvvm observers android-viewmodel
1个回答
0
投票

我缺少一些东西。 viewModel和firstViewModel是同一对象吗?另外,如果是这样,您确定要创建Activity的ViewModel,而不是Fragment吗?

 mViewModel = ViewModelProviders.of(requireActivity()).get(YourViewModel.class);
© www.soinside.com 2019 - 2024. All rights reserved.