我正在尝试在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
}
答案 0 :(得分:0)
直到在getView()中创建了项目视图并将其绑定到listview并进行requestLayout()为止,子项的宽度和高度是未知的。就布局过程而言,这是自然过程,并且可能会在回收生成的视图后从其获取宽度和高度值。可能有一种方法可以覆盖ImageView上的onLayout以在第一次调用时对其进行处理。
答案 1 :(得分:0)
尝试这样做
imageView.measure(0, 0);
imageView.getMeasuredHeight();
imageView.getMeasuredWidth();