gpt4 book ai didi

Android:SaveState、Fragments 和 ViewModel:我做错了什么?

转载 作者:行者123 更新时间:2023-12-02 04:23:34 52 4
gpt4 key购买 nike

按照 Google 的建议,我有一个顶部有多个 fragment 的单一 Activity 。在一个 fragment 中,我希望放置一个开关,并且当我从其他 fragment 返回时,我希望仍然知道它的状态。示例:我在 fragment 一中,然后我打开开关,导航到 fragment 二或 fragment 三,返回到 fragment 一,我希望在离开时将开关置于打开位置加载该 fragment 。

我曾尝试复制google advocates提供的示例,只是为了看到代码失败而什么都不做。

/////////////////////////////////////////////////////////////////
//Inside the first fragment:
class myFragment : Fragment() {

companion object {
fun newInstance() = myFragment()
}

private lateinit var viewModel: myViewModel

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.my_fragment, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)

**viewModel = ViewModelProvider(this, SavedStateVMFactory(this)).get(myViewModel::class.java)

//Here I was hoping to read the state when I come back.
switch_on_off.isChecked = viewModel.getSwRoundTimerInit()**

subscribeToLiveData() //To read liveData

switch_on_off.setOnCheckedChangeListener { _, isChecked ->
viewModel.setOnOff(isChecked)
}
}//End of onActivityCreated
//other code...

/////////////////////////////////////////////////////////////////////////
//On the fragment ViewModel

class myViewModel(private val **mState: SavedStateHandle**) : ViewModel() {

//SavedStateHandle Keys to save and restore states in the App
private val swStateKey = "SW_STATE_KEY"

private var otherSwitch:Boolean //other internal states.

//Init for the other internal states
init {
otherSwitch = false
}

fun getSwRoundTimerInit():Boolean{
val state = mState[swStateKey] ?: "false"
return state.toBoolean()
}

fun setOnOff(swValue:Boolean){
mState.set(swStateKey, swValue.toString())
}

}

这是行不通的。它始终加载默认(关闭)值,就好像 savedState 始终为 null。

最佳答案

改变

//fragment scope
viewModel = ViewModelProvider(thisSavedStateVMFactory(this)).get(myViewModel::class.java)

//activity scope
viewModel = activity?.let { ViewModelProviders.of(it,SavedStateVMFactory(this)).get(myViewModel::class.java) }

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

关于Android:SaveState、Fragments 和 ViewModel:我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57135112/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com