android - kotlin 中的双向数据绑定不起作用
问题描述
我正在创建使用 API 的应用程序,并且我在 ViewModel 中有功能,需要城市名称才能从 Web 获取数据。但它不起作用。我已经在 Java Android 中使用过两种方式的数据绑定,但在 Kotlin 的情况下出现了问题。在 CityViewModel 中,我有一个与编辑文本绑定的 ObservableField。这是城市名称的地方,然后在单击按钮后启动 val currentWeatherByCity,但在日志中是来自 API 的响应错误。如果我只将字符串设置为 currentWeatherByCity,例如“London”API 有效,但如果我想使用 ObservableField 应用程序崩溃。
城市景观模型:
class CityViewModel(
private val weatherRepository: WeatherRepository
): ViewModel() {
val city = ObservableField<String>()
private val metric: String = "metric"
val currentWeatherByCity by lazyDeferred {
weatherRepository.getCurrentWeatherByCity(city.get().toString(), metric)
}
}
城市活动:
private fun bindUI() = launch(Dispatchers.Main) {
val cityWeather = cityViewModel.currentWeatherByCity.await()
cityWeather.observe(this@CityActivity, Observer {
if (it == null) return@Observer
})
活动城 xml:
<EditText android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center"
android:foregroundGravity="center_vertical"
android:textColor="@android:color/white"
android:textSize="20sp"
android:text="@={cityViewModel.city}"
android:hint="London/London,uk"
android:id="@+id/city_edit_text"
android:layout_marginEnd="50dp"
app:layout_constraintEnd_toStartOf="@+id/search_city_button"
android:inputType="text"
android:autofillHints="username"/>
我还检查了日志中的 ObservableField,并且城市为空。如果我在 ObservableField 中设置字符串,那么是正确的,API 会获取数据。
解决方案
推荐阅读
- javascript - 在 React 中定义样式时无法更改按钮位置
- android - 如何保存片段状态
- javascript - 使用nodejs方法socket.write将所有数据发送到哪里?
- java - 我如何在springboot中使用休息模板来保存新对象
- rabbitmq - 带有 MQTT 的 RabbitMQ 在连接时发送消息
- sql - Postgresql:一行中多行的值
- android-studio - 无法使用导入包中的成员 (Flutter)
- python - python selenium phantomjs 执行脚本
- ansible - 在 Ansible Tower 上获取部署次数
- c# - 仅将 DataGridView 单元格边框样式设置为选定列