0

Пытаюсь реализовать 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
            }
        }
    }

1 ответ 1

1

Используйте RecyclerView и GridLayoutManager. В нем реализован паттерн ViewHolder который в свою очередь не подгружает сразу все изображения, а только те которые необходимы в данный момент на экране +1.

Ну и судя из вашего кода вам в процессе показа приходится декодить каждое изображение в процессе создания ячейки. Подумайте о том как можно все картинки подготовить заранее и передать уже готовый список изображений в RecyclerView

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.