android 适配器 convertView 中的 ImageView 测量为 0 宽度和 0 高度

ImageView in android adapter convertView is measured as 0 width and 0 height

我正在尝试在 gridView 的适配器 class 中添加缩放图像。 但是在测量缩小图像时,由于某种原因,iView 的高度和宽度为 0。

代码如下:

    override fun getView(i: Int, convertView: View?, viewGroup: ViewGroup): View {
        var cView = convertView
        val (_, name, company, _, imagePath) = mSitesData[i]

        if (cView == null) {
            val layoutInflater = LayoutInflater.from(context)
            cView = layoutInflater.inflate(R.layout.sites_grid_layout, null)
        }
        val iView = cView!!.findViewById(R.id.imageview_cover_art) as ImageView
        val siteName = cView.findViewById(R.id.site_name) as TextView
        val siteCompany = cView.findViewById(R.id.company_name) as TextView

        if (imagePath.length<2){
            iView.setImageResource(R.drawable.camera_item)
        } else {

            val targetW = iView.getWidth() ***// GIVING 0 AS RESULT***
            val targetH = iView.getHeight()

            // Get the dimensions of the bitmap
            val bmOptions = BitmapFactory.Options() // Returns Option Object
            bmOptions.inJustDecodeBounds = true // So it does not run out of memory if image is big
            BitmapFactory.decodeFile(imagePath, bmOptions) // But can still query the size of the image
            val photoW = bmOptions.outWidth
            val photoH = bmOptions.outHeight

            // Determine how much to scale down the image
            val scaleFactor = Math.min(photoW / targetW, photoH / targetH)

            // Decode the image file into a Bitmap sized to fill the View
            bmOptions.inJustDecodeBounds = false
            bmOptions.inSampleSize = scaleFactor

            val bitmap = BitmapFactory.decodeFile(imagePath, bmOptions)
            iView.setImageBitmap(bitmap)

        }

        siteName.text = name
        siteCompany.text = company
        return cView
    }

直到在getView()中创建item view并绑定到listview并发生requestLayout()时,才知道child的宽高。这在布局过程中是一个很自然的过程,它很可能会从生成的视图被回收时得到宽度和高度值。可能有一种方法可以覆盖 ImageView 上的 onLayout 以在第一次调用时处理它。

尝试这样做

 imageView.measure(0, 0);
        imageView.getMeasuredHeight();
        imageView.getMeasuredWidth();