我是一个新手Android开发人员,我试图观察一个布尔集在ViewModel从它的父母的活动。我可以在应用程序启动时观察它的初始状态,但之后应用的任何更改似乎都不会触发观察者(即当我切换片段时)。
下面是我的ViewModel的代码:class MyMusicViewModel : ViewModel() {
private var _MyMusicViewOn = MutableLiveData<Boolean>()
val MyMusicViewOn: LiveData<Boolean> get() = _MyMusicViewOn
init {
Timber.i("MyMusicViewModel Init Called!")
setMyMusicView(true)
}
override fun onCleared() {
super.onCleared()
Timber.i("MyMusicViewModel Cleared!")
setMyMusicView(false)
}
fun setMyMusicView(setter: Boolean) {
Timber.i("MyMusicViewModel setter called! %s", setter)
_MyMusicViewOn.value = setter
}
}
这是它的父activity:
class FullscreenActivity : AppCompatActivity() {
private val viewModel: MyMusicViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.MyMusicViewOn.observe(this, Observer { MyMusicViewOn ->
Timber.i("Observer called for MyMusicViewOn %s", MyMusicViewOn)
})
}
}
如果你想看到ViewModel的相关片段,它在这里:
class MyMusicFragment : Fragment() {
private lateinit var viewModel: MyMusicViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding = DataBindingUtil.inflate<FragmentMyMusicBinding>(
inflater,
R.layout.fragment_my_music,
container,
false
)
viewModel = ViewModelProvider(this).get(MyMusicViewModel::class.java)
return binding.root
}
override fun onResume() {
super.onResume()
Timber.i("MyMusicViewFragment resumed!")
viewModel.setMyMusicView(true)
}
}
我想要完成的是观察onResume(), onCleared()和init{}函数,每当它们通过改变MyMusicViewOn mutableelvedata布尔值的状态被调用时。我不明白的是,为什么布尔不触发观察者设置在父活动每当它的变化。
提前感谢你的任何想法!
祝你一切顺利,
工厂。
我猜,然而,你是填充的viewModel
属性在你的片段,你不使用活动的ViewModel实例。获得活动正在使用的相同实例的最简单方法是使用activityViewModels
委托:
private val viewModel: MyMusicViewModel by activityViewModels()