如何让 MutableLiveData<String> 触发 onChanged?

Wal*_*ann 1 android kotlin android-livedata mutablelivedata

请帮帮我。
我想使用LiveData.
OnChanged()在应用程序启动时触发一次,但是当我string1通过单击按钮更改值时,onChange()不会触发并且信息不会更新。TextView一直显示“哇”
我完全按照这里的描述做所有事情。
ViewModel

class CurrentViewModel : ViewModel() {


val currentName: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
}
}
Run Code Online (Sandbox Code Playgroud)

片段:

class CurrentFragment : Fragment(R.layout.current_fragment) {
        private val viewModel: CurrentViewModel by viewModels()
       var string1 = "Wow!"

  override fun onActivityCreated(savedInstanceState: Bundle?)
       val nameObserver = Observer<String> { newName ->
            textview.text = newName        }
       viewModel.currentName.value = string1
       viewModel.currentName.observe(activity!!, nameObserver)


   button.setOnClickListener {
            string1 = "some new string"
        }
}
Run Code Online (Sandbox Code Playgroud)

Ped*_*ngo 5

您没有更新 的值,viewModel.currentName您应该始终更新MutableLiveData的值以通知观察者。

在你OnClickListener做的里面:

button.setOnClickListener {
    // update viewModel value to notify listeners/observers
    viewModel.currentName.value = "some new string"
}
Run Code Online (Sandbox Code Playgroud)

Obs:你可以删除,string1因为它没有用!