0

我正在尝试创建一个在从服务器下载图像时显示的进度条。此图像被加载到自定义视图中。(我需要它是自定义的,因为我在图像上绘制。)

我的解决方案是将自定义视图添加到片段布局下的 XML 中,并将其可见性标记为 Visibility.GONE。这在 XML 编辑器中有效,因为进度条占据了整个空间。隐形不起作用,因为它的位置仍然显示。

当图像路径提供给我的自定义视图时,问题就出现了。似乎在视图上设置 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()。有没有更好的方法来处理这个问题,如果没有,是否有办法强制代码等到我知道视图已经完成了它的测量过程?

4

1 回答 1

0

使用带有匿名类内联的基本侦听器模式解决。我不确定是否有更好的方法,但这种方法效果很好。延迟不是什么大问题,因为无论如何视图绘制得相当快。

     * 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)
                    }
                }
            })
        }
于 2020-06-04T12:10:38.577 回答