我正在尝试实现一个显示资产照片的 GridView。一切正常,但滚动时,图片出现延迟。你会有什么建议和建议?
inner class ImageAdapter(private val mContext: Context) : BaseAdapter() {
private val am: AssetManager = mContext.assets
private val files: Array<String>? = am.list("img")
override fun getCount(): Int {
return files!!.size
}
override fun getItem(position: Int): Any? {
return null
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
if (convertView == null) {
val layoutInflater = LayoutInflater.from(mContext)
convertView = layoutInflater.inflate(R.layout.choose_element, null)
}
val imageView = convertView!!.findViewById<ImageView>(R.id.gridImageview)
imageView.post {
object : AsyncTask<Void?, Void?, Void?>() {
private var bitmap: Bitmap? = null
override fun onPostExecute(aVoid: Void?) {
super.onPostExecute(aVoid)
imageView.setImageBitmap(bitmap)
}
override fun doInBackground(vararg p0: Void?): Void? {
if (!listId.contains(position)) {
bitmap = getPicFromAsset(imageView, files!![position])
list.add(bitmap!!)
listId.add(position)
} else {
bitmap = list[position]
}
return null
}
}.execute()
}
return convertView
}
private fun getPicFromAsset(imageView: ImageView, assetName: String): Bitmap? {
val targetW = imageView.width
val targetH = imageView.height
return if (targetW == 0 || targetH == 0) {
null
} else try {
val `is` = am.open("img/$assetName")
val bmOptions = BitmapFactory.Options()
bmOptions.inJustDecodeBounds = true
BitmapFactory.decodeStream(`is`, Rect(-1, -1, -1, -1), bmOptions)
val photoW = bmOptions.outWidth
val photoH = bmOptions.outHeight
val scaleFactor = (photoW / targetW).coerceAtMost(photoH / targetH)
`is`.reset()
bmOptions.inJustDecodeBounds = false
bmOptions.inSampleSize = scaleFactor
bmOptions.inPurgeable = true
BitmapFactory.decodeStream(`is`, Rect(-1, -1, -1, -1), bmOptions)
} catch (e: IOException) {
FirebaseCrash.report(e); // Generate report
e.printStackTrace()
null
}
}
}
使用 RecyclerView 和 GridLayoutManager。它实现了 ViewHolder 模式,反过来,它不会一次加载所有图像,而只会加载屏幕上当前需要的图像 +1。
好吧,从你的代码来看,在显示过程中,你必须在创建单元格的过程中解码每个图像。想想如何提前准备好所有的图片,把已经准备好的图片列表传给 RecyclerView