I stumbled upon a problem while coding my application. I'm using databinding for display data on the screen - for that I use LiveData. My problem is that the binding always returns null, but if I observe this data it gives back the right result. What do I do wrong? (I'm talking about feelsLikeDegree livedata)
XML code:
<TextView
android:id="@+id/tv_degrees_feels_like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:text="@{@string/feels_like(String.valueOf(viewmodel.feelsLikeDegree))}"
android:textSize="13sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_degrees" />
ViewModel:
@HiltViewModel
@SuppressLint("StaticFieldLeak")
class WeatherViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val repository: WeatherRepository
): ViewModel() {
private val _resp = MutableLiveData<WeatherResponse>()
val weatherResp: LiveData<WeatherResponse>
get() = _resp
private val _feelsLikeDegree = MutableLiveData<Double>()
val feelsLikeDegree: LiveData<Double>
get() = _feelsLikeDegree
init {
getWeather()
}
private fun getWeather() = viewModelScope.launch {
if (hasInternetConnection()) {
repository.getWeatherInfo("47.497913", "19.040236", listOf(), "metric", API_KEY)
.let { response ->
if (response.isSuccessful) {
_resp.postValue(response.body())
_feelsLikeDegree.postValue(response.body()?.current?.feels_like)
}
}
} else {
Log.e("asdfg", "no internet")
}
}
}
也许您忘记在您的活动或片段中设置 binding.lifecycleOwner
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.