【发布时间】:2020-09-12 15:14:33
【问题描述】:
我正在尝试将可绘制对象与实时数据数据绑定并遇到此错误
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)}"
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
您是否将
viewModel设置为片段/活动的绑定类? -
@ManoharReddy override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_daily_weather, container, false) binding.lifecycleOwner = this return binding.root }
标签: android android-databinding android-livedata