我正在尝试在 BindingAdapter
函数中处理 LiveData
值(profilePicture: Bitmap
),但第一个值始终是 null。绑定(bind)适配器是一个带有 ProgressBar
和 ImageView
的 ViewSwitcher
。
像这样从 firebase 获取个人资料图片:
val downloadPictureResult = MutableLiveData<Bitmap>()
// ...
fun downloadProfilePic(): LiveData<Bitmap?> {
val imageRef = storage.getReference("images/$uid/profile/profile_picture.jpg")
imageRef.getBytes(ONE_MEGABYTE).addOnCompleteListener { task ->
if (task.isSuccessful) {
//...
downloadPictureResult.value = responseBitmap
//...
} else {
downloadPictureResult.value = null
Log.d(TAG, task.exception?.localizedMessage)
}
}
return downloadPictureResult;
}
因为第一个值是null,第二个是预期的位图对象,view.showNext()
被调用了两次。但对我来说更重要的是要理解为什么 firstvalue 是 null 因为 setProfilePicture
方法会有更多的逻辑。
BindingAdapter 看起来像这样。
fun setProfilePicture(view: ViewSwitcher, profilePicture: Bitmap?) {
Log.d("PPSS", profilePicture.toString())
val imageView: ImageView = view[1] as ImageView
imageView.setImageDrawable(view.context.getDrawable(R.drawable.account_circle_24dp))
profilePicture.let { picture ->
if (picture != null) {
val rounded = RoundedBitmapDrawableFactory.create(view.resources, picture)
rounded.isCircular = true
imageView.setImageDrawable(rounded)
view.showNext()
} else {
view.showNext()
}
}
Log:
2019-04-13 17:53:01.658 11158-11158/... D/PPSS: null
2019-04-13 17:53:02.891 11158-11158/... D/PPSS: android.graphics.Bitmap@8b6ecb8
最佳答案
当你定义一个LiveData
时,即使它的类型不可为空,它的初始值也会为null:
val downloadPictureResult = MutableLiveData<Bitmap>()
// Here, downloadPictureResult.value is null
在您的情况下,downloadProfilePic()
返回的 LiveData
的值在图片下载之前将为空,这将在回调 内异步发生addOnCompleteListener
:
fun downloadProfilePic(): LiveData<Bitmap?> {
...
imageRef.getBytes(ONE_MEGABYTE).addOnCompleteListener { task ->
...
// This happens asynchronously, likely after downloadProfilePic()
// has already returned
downloadPictureResult.value = responseBitmap
...
}
return downloadPictureResult;
}
这就是为什么传递给你的适配器的第一个值是空的,因为当 downloadProfilePic 返回
第一次。downloadPictureResult
时 downloadPictureResult.value
仍然是空()
关于android - BindingAdapter LiveData 第一个值始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667645/