我正试图创建一个进度条,在图像从服务器下载时显示。 这个图像被加载到一个自定义的视图中。 我需要它是自定义的,因为我在图像上画画)。
我的解决方案是将自定义视图添加到XML片段布局下,并将其可见性标记为Visibility.GONE。 这在XML编辑器中有效,因为进度条占据了整个空间。 Invisible不起作用,因为它的位置仍然被显示。
当图像路径被赋予我的自定义视图时,问题就来了。 似乎在视图上设置Visibility.GONE就意味着不测量视图的尺寸。 但是我需要视图的尺寸来测量位图应该有多大。
// Create the observer which updates the UI.
val photoObserver = Observer<String?> { photoPath ->
spinner.visibility = View.GONE
thumbnailFrame.visibility = View.VISIBLE
thumbnailFrame.invalidate()
thumbnailFrame.setImage(photoPath)
从自定义视图的日志来看,它正在调用onMeasured(),但做得太晚了。 我需要在setImage()之前调用onMeasure()。 有没有更好的方法来处理这个问题,如果没有,有没有办法强制代码等待,直到我知道视图已经完成了它的测量过程?
使用一个基本的监听器模式和一个内联的匿名类来解决。 我不知道是否有更好的方法,但这种方式就很好。 延迟并不是什么问题,因为无论如何视图的绘制速度是相当快的。
* Set a listener to notify parent fragment/activity when view has been measured
*/
fun setViewReadyListener(thumbnailHolder: ViewReadyListener) {
holder = thumbnailHolder
}
interface ViewReadyListener {
fun onViewSet()
}
private fun notifyViewReadyListener() {
holder?.onViewSet()
}
spinner.visibility = View.INVISIBLE
thumbnailFrame.visibility = View.VISIBLE
//We have to make sure that the view is finished measuring before we attempt to put in a picture
thumbnailFrame.setViewReadyListener(object : ThumbnailFrame.ViewReadyListener {
override fun onViewSet() {
thumbnailFrame.setImage(photoPath)
//If we have a previous saved state, load it here
val radius = viewModel.thumbnailRadius
val xPosit = viewModel.thumbnailXPosit
val yPosit = viewModel.thumbnailYPosit
if (radius != null) {
thumbnailFrame.setRadius(radius)
}
if (xPosit != null) {
thumbnailFrame.setRadius(xPosit)
}
if (yPosit != null) {
thumbnailFrame.setRadius(yPosit)
}
}
})
}