首页 > 解决方案 > kotlin 中的双向数据绑定不起作用

问题描述

我正在创建使用 API 的应用程序,并且我在 ViewModel 中有功能,需要城市名称才能从 Web 获取数据。但它不起作用。我已经在 J​​ava 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 会获取数据。

标签: androidkotlinandroid-databindingandroid-mvvm

解决方案


推荐阅读