代码之家  ›  专栏  ›  技术社区  ›  Javallion

在Android适配器中测量的是0的宽度和0的高度。

  •  0
  • Javallion  · 技术社区  · 6 年前

    我试图在GRIDVIEW中在适配器类中添加一个缩放图像。 但是当测量图像缩小时,由于某些原因,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
        }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   pistolcaffe    6 年前

    在getview()中创建项视图并绑定到listview和requestlayout()之前,子项的宽度和高度是未知的。这是一个自然的过程,在布局过程中,它可能会获得宽度和高度值从生成的视图被回收的时间。可能有一种方法可以覆盖imageview上的onlayout,以便在第一次调用时处理它。

        2
  •  0
  •   Rohit Sharma    6 年前

    试着做这个

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