В приложении у меня есть действие, в котором размещается свернутая компоновка панели инструментов и представление переработчика, которое я получил должным образом, однако здесь возникает проблема, когда я пытаюсь прокрутить свое представление переработчика, это вызывает огромные лаги, которые, в свою очередь, приводят к закрытию UI / UX здесья пытаюсь загрузить большое количество изображений в режиме рециркуляции, скажем, 600–800 изображений загружаются асинхронно с помощью glide и процедур, несмотря на это, если я удаляю вызов загрузки изображений из glide, все же recyclerview вызывает те же лаги, что и раньше. Я действительно не могу интерпретировать причину этой проблемы! Мы будем благодарны за любую помощь!
Вот мой класс адаптера: класс MainFolderImagesAdapter:
RecyclerView.Adapter<RecyclerView.ViewHolder> {
private var thumbPaths = ArrayList<String>()
private val tempThumbPath = ArrayList<String>()
private var context: Activity? = null
private var albumName: String? = null
private val al_selected_photo = ArrayList<Int>()
private var mItemCLickAlbumImageListener: ItemCLickAlbumImageListener? = null
private var mDatabaseHelper: DatabaseHelper? = null
private var mBean: Bean? = null
constructor(thumbPaths: ArrayList<String>, albumName: String, databaseHelper: DatabaseHelper, applicationContext: Activity, bean: Bean) {
this.mBean = bean
this.context = applicationContext
this.albumName = albumName
this.mDatabaseHelper = databaseHelper
Share.selected_image_no.clear()
this.thumbPaths = thumbPaths
}
protected inner class LoadingVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
val mProgressBar: ProgressBar
init {
mProgressBar = itemView.findViewById(R.id.pbar)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): RecyclerView.ViewHolder {
var viewHolder1: RecyclerView.ViewHolder? = null
val inflater = LayoutInflater.from(viewGroup.context)
when (i) {
ITEM -> {
val view1 = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_show_image, viewGroup, false)
viewHolder1 = ViewHolder(view1)
return ViewHolder(view1)
}
LOADING -> {
val viewLoading = inflater.inflate(R.layout.custom_loading_list_item, viewGroup, false)
viewHolder1 = LoadingVH(viewLoading)
}
}
// View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_show_image, viewGroup, false);
return viewHolder1!!
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: List<Any>) {
super.onBindViewHolder(holder, position, payloads)
when (getItemViewType(position)) {
ITEM -> {
val movieVH = holder as ViewHolder
if (payloads.contains("maulik")) {
movieVH.progress.visibility = View.GONE
movieVH.iv_complete.visibility = View.VISIBLE
} else if (payloads.contains("123")) {
movieVH.iv_background.visibility = View.GONE
movieVH.iv_selected.visibility = View.GONE
}
}
LOADING -> {
val loadingVH = holder as LoadingVH
loadingVH.mProgressBar.visibility = View.VISIBLE
}
}
}
override fun onBindViewHolder(holder1: RecyclerView.ViewHolder, i: Int) {
//holder1.setIsRecyclable(false)
when (getItemViewType(i)) {
ITEM -> {
val holder = holder1 as ViewHolder
var uniqueID: Int?=null
if (Share.checkUserType(context)) {
GlobalScope.async(Dispatchers.Default) {
uniqueID = mDatabaseHelper!!.getImagesUniqueID(albumName,
getOriginalFilename(thumbPaths[i]), DatabaseHelper.IMAGES_TABLE)
}
} else {
GlobalScope.async(Dispatchers.Default) {
uniqueID = mDatabaseHelper!!.getImagesUniqueIDGuest(albumName,
getOriginalFilename(thumbPaths[i]), DatabaseHelper.IMAGES_TABLE)
}
}
if (Share.checkUserType(context)) {
// if (SharedPrefs.getBoolean(context, SharedPrefs.AutoUploadEnable)) {
if (uniqueID!! > 0) {
holder.progress.visibility = View.GONE
holder.iv_complete.visibility = View.VISIBLE
} else {
holder.progress.visibility = View.VISIBLE
holder.iv_complete.visibility = View.GONE
}
} else {
holder.progress.visibility = View.GONE
holder.iv_complete.visibility = View.GONE
}
if (!SharedPrefs.getBoolean(context, SharedPrefs.AutoUploadEnable)) {
holder.progress.visibility = View.GONE
}
if (al_selected_photo.size > 0) {
if (al_selected_photo.contains(uniqueID)) {
holder.iv_selected.visibility = View.VISIBLE
holder.iv_background.visibility = View.VISIBLE
} else {
holder.iv_selected.visibility = View.GONE
holder.iv_background.visibility = View.GONE
}
} else {
holder.iv_selected.visibility = View.GONE
holder.iv_background.visibility = View.GONE
}
try {
GlobalScope.async(Dispatchers.Default) {
var arr:ByteArray?=null
val op = GlobalScope.async(Dispatchers.Default){
arr = ImageEncryptDecrypt.decrypt(context, thumbPaths[i])
}
op.await()
withContext(Dispatchers.Main) {
Glide.with(context)
.load(arr)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.thumbnail(0.9f)
.skipMemoryCache(false)
.centerCrop()
.placeholder(R.drawable.dummy_header_bg)
.listener(object : RequestListener<ByteArray, Bitmap> {
override fun onException(e: Exception, model: ByteArray, target: Target<Bitmap>, isFirstResource: Boolean): Boolean {
return false
}
override fun onResourceReady(resource: Bitmap, model: ByteArray, target: Target<Bitmap>, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
Log.e("Digan--->>", "onResourceReady: " + "redyyyyy")
if (MainFolderImagesActivity.mDownloadImageDialog != null && MainFolderImagesActivity.mDownloadImageDialog!!.isShowing) {
MainFolderImagesActivity.mDownloadImageDialog!!.dismiss()
MainFolderImagesActivity.mDownloadImageDialog = null
}
Glide.get(context).clearMemory()
return false
}
})
.into(holder.all_image_iv_view)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
holder.itemView.setOnClickListener(object : OnSingleClickListener() {
override fun onSingleClick(v: View) {
if (Share.downloadComplete) {
if (uniqueID!! > 0) {
if (al_selected_photo.size > 0) {
if (!al_selected_photo.contains(uniqueID!!)) {
if (al_selected_photo.size < 20) {
al_selected_photo.add(uniqueID!!)
Share.selected_image_no.add(uniqueID)
holder.iv_background.visibility = View.VISIBLE
holder.iv_selected.visibility = View.VISIBLE
if (mItemCLickAlbumImageListener != null) {
if (al_selected_photo.size == 0) {
mItemCLickAlbumImageListener!!.itemClicked(i, al_selected_photo.size, holder.iv_selected)
}
MainFolderImagesActivity.tv_count.text = Share.selected_image_no.size.toString() + " Selected"
}
} else {
Toast.makeText(context!!.applicationContext, "you can select maximum 20 images", Toast.LENGTH_SHORT).show()
}
} else {
val pos = al_selected_photo.indexOf(uniqueID!!)
al_selected_photo.removeAt(pos)
Share.selected_image_no.removeAt(pos)
holder.iv_background.visibility = View.GONE
holder.iv_selected.visibility = View.GONE
if (mItemCLickAlbumImageListener != null) {
if (al_selected_photo.size == 0) {
mItemCLickAlbumImageListener!!.itemClicked(i, al_selected_photo.size, holder.iv_selected)
}
MainFolderImagesActivity.tv_count.text = Share.selected_image_no.size.toString() + " Selected"
}
}
} else {
mBean!!.thumbPaths = thumbPaths
val intent = Intent(context, ViewImageActivity::class.java)
intent.putExtra("pos", holder.adapterPosition)
intent.putExtra("fromWhere", "albumImages")
context!!.startActivity(intent)
}
}
}
}
})
holder.itemView.setOnLongClickListener { v ->
if (Share.downloadComplete) {
//int uniqueID1 = mDatabaseHelper.getImagesUniqueID(albumName, getOriginalFilename(thumbPaths.get(i)), DatabaseHelper.IMAGES_TABLE);
var uniqueID1: Int?=null
if (Share.checkUserType(context)) {
GlobalScope.async(Dispatchers.Default) {
uniqueID1 = mDatabaseHelper!!.getImagesUniqueID(albumName,
getOriginalFilename(thumbPaths[i]), DatabaseHelper.IMAGES_TABLE)
}
} else {
GlobalScope.async(Dispatchers.Default) {
uniqueID1 = mDatabaseHelper!!.getImagesUniqueIDGuest(albumName,
getOriginalFilename(thumbPaths[i]), DatabaseHelper.IMAGES_TABLE)
}
System.gc()
Runtime.getRuntime().gc()
}
if (uniqueID!! > 0) {
if (al_selected_photo.size == 0) {
if (!al_selected_photo.contains(uniqueID1)) {
if (al_selected_photo.size < 20) {
Share.selected_image_no.add(uniqueID1)
al_selected_photo.add(uniqueID1!!)
holder.iv_selected.visibility = View.VISIBLE
holder.iv_background.visibility = View.VISIBLE
if (mItemCLickAlbumImageListener != null) {
mItemCLickAlbumImageListener!!.itemClicked(i, al_selected_photo.size, holder.iv_selected)
}
MainFolderImagesActivity.tv_count.text = Share.selected_image_no.size.toString() + " Selected"
} else {
Toast.makeText(context!!.applicationContext, "you can select maximum 20 images", Toast.LENGTH_SHORT).show()
}
} else {
val pos = al_selected_photo.indexOf(uniqueID1)
Share.selected_image_no.removeAt(pos)
al_selected_photo.removeAt(pos)
holder.iv_selected.visibility = View.GONE
holder.iv_background.visibility = View.GONE
if (mItemCLickAlbumImageListener != null) {
mItemCLickAlbumImageListener!!.itemClicked(i, al_selected_photo.size, holder.iv_selected)
}
MainFolderImagesActivity.tv_count.text = Share.selected_image_no.size.toString() + " Selected"
}
}
}
}
true
}
}
LOADING -> {
val loadingVH = holder1 as LoadingVH
loadingVH.mProgressBar.visibility = View.GONE
}
}
}
override fun getItemViewType(position: Int): Int {
return if (isLoadingAdded) {
if (isLoadingAdded) ITEM else LOADING
} else {
if (position == thumbPaths.size - 1) LOADING else ITEM
}
}
private fun getOriginalFilename(path: String?): String {
return (if (path != null) {
File(path).name
} else path)!!
}
fun setItemClickListener(itemClickListener: ItemCLickAlbumImageListener) {
this.mItemCLickAlbumImageListener = itemClickListener
}
override fun getItemCount(): Int {
Log.e("getItemCount", "getItemCount: " + thumbPaths.size)
return thumbPaths.size
// /*return thumbPaths.size();*/
}
fun unSelectAll() {
for (i in al_selected_photo.indices) {
GlobalScope.async(Dispatchers.Default) {
val path = mDatabaseHelper!!.getImagesStringFromUniqID(al_selected_photo[i], null, DatabaseHelper.IMAGES_TABLE)
notifyItemChanged(thumbPaths.indexOf(path), "123")
}
}
Share.selected_image_no.clear()
al_selected_photo.clear()
}
fun removeItems(selectedItemsThumbs: ArrayList<String>) {
for (i in selectedItemsThumbs.indices) {
thumbPaths.remove(selectedItemsThumbs[i])
notifyItemRemoved(thumbPaths.indexOf(selectedItemsThumbs[i]))
notifyItemRangeChanged(thumbPaths.indexOf(selectedItemsThumbs[i]), itemCount)
}
(context as MainFolderImagesActivity).changeCount(thumbPaths.size)
al_selected_photo.clear()
notifyDataSetChanged()
}
fun updateResult(imageItems: ArrayList<String>) {
thumbPaths.addAll(imageItems)
notifyItemRangeInserted(0, itemCount)
(context as MainFolderImagesActivity).changeCount(thumbPaths.size)
}
fun updateResult1(imageItems: ArrayList<String>) {
thumbPaths.addAll(imageItems)
notifyItemRangeInserted(itemCount, thumbPaths.size)
}
internal inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var all_image_iv_view: ImageView
var iv_selected: ImageView
var iv_background: ImageView
var iv_complete: ImageView
var progress: ProgressBar
init {
all_image_iv_view = itemView.findViewById(R.id.all_image_iv_view)
iv_background = itemView.findViewById(R.id.iv_background)
iv_selected = itemView.findViewById(R.id.iv_selected)
progress = itemView.findViewById(R.id.progress)
iv_complete = itemView.findViewById(R.id.iv_complete)
val displayMetrics = DisplayMetrics()
context!!.windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
all_image_iv_view.requestLayout()
all_image_iv_view.layoutParams.height = width / 3
all_image_iv_view.layoutParams.width = width / 3
iv_background.setBackgroundColor(mBean!!.themeColor)
}
}
fun add(response: String) {
if (!thumbPaths.contains(response)) {
thumbPaths.add(0, response)
notifyItemInserted(0)
notifyItemRangeChanged(0, itemCount)
(context as MainFolderImagesActivity).rcv_images.scrollToPosition(0)
(context as MainFolderImagesActivity).changeCount(thumbPaths.size)
} else {
Logs.e("add", "add: ")
notifyItemChanged(thumbPaths.indexOf(response), "maulik")
}
}
fun setValue(thumbPath: String, path: String) {
if (thumbPaths.contains(thumbPath)) {
Logs.e("setValue", "setValue: " + thumbPaths.indexOf(thumbPath))
thumbPaths[thumbPaths.indexOf(thumbPath)] = path
notifyItemChanged(thumbPaths.indexOf(path), "maulik")
}
}
fun addAll(postItems: List<String>) {
for (response in postItems) {
add(response)
}
}
companion object {
private var isLoadingAdded = false
// View Types
private val ITEM = 0
private val LOADING = 1
}
}
Примечание. Я уже добавил эти флаги в утилите просмотра
rcv_images.setHasFixedSize(true)
rcv_images.isNestedScrollingEnabled = false
rcv_images.setItemViewCacheSize(20)
Вот ссылка на код XML:
https://pastebin.com/F9wrrYpA