[英]How to use Live Data correctly in my case Android kotlin
HomeFragment Everything seems to be done correctly, but when you flip the screen, the resulting value from the EditText disappears from the TextView. What to do tell me pls HomeViewModel MainActivity HomeFragment一切似乎都已正确完成,但是当您翻转屏幕时,EditText 的结果值从 TextView 中消失。该怎么做请告诉我HomeViewModel MainActivity
Try replacing:尝试更换:
viewModel.myValue.observe(viewLifecycleOwner) {
binding.txtResult.text = viewModel.myValue.value
}
with和
viewModel.myValue.observe(viewLifecycleOwner) {
binding.txtResult.text = it
}
what you are doing wrong is that you start observing the value from the viewmodel only after you click btnSend
.您做错的是只有在单击
btnSend
后才开始观察 viewmodel 的值。 This creates two problems.这产生了两个问题。 The first is the obvious one you have found already.
第一个是你已经找到的明显的。 You lose the value upon rotating because you have a new View.
因为你有一个新的视图,所以你在旋转时失去了价值。 The second one is that every time you click on btnSend you are re-observing your LiveData with a new observer object.
第二个是每次你点击 btnSend 时,你都会用一个新的观察者 object 重新观察你的 LiveData。
You have to move the folowing code inside your OnCreateView
after setting the binding
value设置
binding
值后,您必须在OnCreateView
中移动以下代码
viewModel.myValue.observe(viewLifecycleOwner) {
binding.txtResult.text = viewModel.myValue.value
}
You can also replace the second part of the assignment with just it
as it is suggested in the answer from @JustSightseeing您也可以按照@JustSightseeing 的答案中的建议,将作业的第二部分替换为
it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.