简体   繁体   English

如何在我的案例中正确使用实时数据 Android kotlin

[英]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.

相关问题 如何在Android中通过https正确下载文件(在我的情况下为zip)? - How to correctly download a file (zip in my case) through https in Android? Android开发中Kotlin合约的用例是什么 - What is the use case for Kotlin contracts in Android development 如何使用 MVVM 从 android studio Kotlin 中的谷歌地图标记的 api 调用实时数据 - How to call live data from a api for google maps marker in android studio Kotlin using MVVM 如何在 Kotlin 中正确使用字符串属性? - How to use string property correctly in Kotlin? 如何在 Android Kotlin 上正确添加片段? - How to correctly add fragments on Android Kotlin? 如何正确实现corroutines/room? Kotlin Android - How to implement corroutines/room correctly? Kotlin Android 如何在数据模块中使用Android Kotlin Dagger 2和Firebase Auth? - How to use Android Kotlin Dagger 2 and Firebase Auth in Data module? 如何在android(kotlin)中使用双向数据绑定 - How to use Two-way data binding in android (kotlin) 如何使用 Android kotlin 内部常量格式化 GPS 位置数据 - How to use Android kotlin internal constants for formatting GPS location data 如何在 Android Studio 3.0.0 中使用数据绑定和 Kotlin - How to use Data Binding and Kotlin in Android Studio 3.0.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM