我有一个Activity,其中包含一个带有视图模型的片段。活动需要能够更新实时数据对象的值以及片段。
我为片段声明了我的ViewModel:
class BottomNavViewModel:ViewModel() {
var isConnected = MutableLiveData<Boolean>()
}
在BottomNavFragment中,我有这段代码来声明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
}
}
在日志中,我看到指示更新已发生但观察者从未收到该消息的消息。
有人可以告诉我我在做什么错吗?
答案 0 :(得分:1)
您的2个视图模型不相同。您正在创建一个视图模型并传递生命周期所有者,在一种情况下,您指定片段,在另一种情况下,您指定活动。
像这样更改片段:
private val viewModel: BottomNavViewModel by lazy { ViewModelProviders.of(activity).get(BottomNavViewModel::class.java) }
请注意在初始化视图模型的位置,因为activity
(getActivity()
)是nullable
。
编辑:(信贷Ian Lake)或者,如果您使用fragment-ktx
工件,则可以这样做
private val viewModel: BottomNavViewModel by activityViewModels()