我正在尝试将一个drawable与实时数据进行数据绑定,并遇到以下错误
java.lang.RuntimeException: Failed to call observer method
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
我的xml片段(仅粘贴了相关部分)
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="androidx.core.content.ContextCompat" />
<variable name="location" type="String"/>
<variable name="viewModel"
type="com.marty.dang.polarpointsweatherapp.presentation.viewmodel.DailyWeatherViewModel"/>
</data>
<ImageView
android:id="@+id/homeFrag_weather_icon"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="40dp"
android:src="@{ContextCompat.getDrawable(context, viewModel.iconObservable)}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/homeFrag_title_text_view" />
我的视图模型(仅粘贴了相关部分)
val iconObservable: MutableLiveData<Int> by lazy { MutableLiveData<Int>() }
private fun determineWeatherIcon(weatherDescription: String) {
val icon = when(weatherDescription){
"Thunderstorm" -> R.drawable.thunderstorm_icon
"Drizzle" -> R.drawable.rain_icon
"Rain" -> R.drawable.rain_icon
"Snow" -> R.drawable.snow_icon
"Clear" -> R.drawable.sun_icon
"Clouds" -> R.drawable.cloudy_icon
else -> R.drawable.cloudy_icon
}
iconObservable.postValue(icon)
}
我的可绘制文件夹
但是,如果我只使用一个常规变量,而不是一个可变的实时数据变量,那么它工作得很好。
var weatherIcon = R.drawable.snow_icon
private fun determineWeatherIcon(weatherDescription: String) {
weatherIcon = when(weatherDescription){
"Thunderstorm" -> R.drawable.thunderstorm_icon
"Drizzle" -> R.drawable.rain_icon
"Rain" -> R.drawable.rain_icon
"Snow" -> R.drawable.snow_icon
"Clear" -> R.drawable.sun_icon
"Clouds" -> R.drawable.cloudy_icon
else -> R.drawable.cloudy_icon
}
}
android:src="@{ContextCompat.getDrawable(context, viewModel.weatherIcon)}"
如有任何帮助,我们将不胜感激。谢啦!
iconObservable.value在xml上尝试一下,它会起作用的