Пытаюсь реализовать GridView, который отображает фотографии из assets. Всё работает, но при прокручивании картинки появляются с задержкой. Какие могут быть ваши советы и рекомендации ?
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
}
}
}