我的活动中有一个带有viewModel的片段。该活动需要能够更新Livedata对象的值以及片段。
我为这样的片段声明了我的ViewModel:
class BottomNavViewModel:ViewModel() {
var isConnected = MutableLiveData<Boolean>()
}
在底部navfragment中,我有此代码来声明ViewModel
private val viewModel: BottomNavViewModel by lazy { ViewModelProviders.of(this).get(BottomNavViewModel::class.java) }
我有几行:
private val changeObserver = Observer<Boolean> { value ->
value?.let {
Timber.i("Update of isConnected received. Updating text field now")
if(it) {
connectedText.text = getString(R.string.connected)
connectedText.setTextColor(activity!!.getColor(R.color.colorSelectedGreen))
}
else {
connectedText.text = getString(R.string.not_connected)
connectedText.setTextColor(activity!!.getColor(R.color.off_red))
}
}
...
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is BottomNavFragment.OnFragmentInteractionListener) {
listener = context
}
else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
viewModel.isConnected.observe(this, changeObserver)
}
那个观察者永远不会被击中。
在我的活动中,我有一个:
private var sharedBottomNavViewModel:BottomNavViewModel? = null
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_connection)
sharedBottomNavViewModel = ViewModelProviders.of(this).get(BottomNavViewModel::class.java)
...
override fun onResume() {
super.onResume()
startBackgroundThread()
checkCameraPermission()
//TODO: Change this to listen for a connection
sharedBottomNavViewModel?.let {
Timber.i("Updating isConnected to true now")
it.isConnected.value = true
}
}
在日志中,我看到了表示更新的消息,但观察者永远不会收到消息。
谁能告诉我我在这里做错了什么?
您的2个视图模型不是相同的。您正在创建一个ViewModel并通过生命周期所有者,在一种情况下,您指定了片段,而在另一个情况下则是活动。
这样更改片段:
private val viewModel: BottomNavViewModel by lazy { ViewModelProviders.of(activity).get(BottomNavViewModel::class.java) }
请小心在哪里初始化ViewModel,因为activity
(getActivity()
(是nullable
。
编辑:(信用Ian Lake(,或者,如果您使用fragment-ktx
工件,则可以执行此操作
private val viewModel: BottomNavViewModel by activityViewModels()