В моем приложении я реализовал библиотеку подкачки Google, здесь я могу успешно загружать данные в recyclerView, во-первых, 30 изображений будут загружены из массива, а затем, когда пользователь прокрутит страницу вниз, я хочу, чтобы пользователь показывал следующие 30 изображений издля этого я реализовал класс PageKeyedDatasouce, где onloadafter вызывается, когда моя прокрутка recyclerView внизу ничего не происходит, и мой recyclerView не обновляется новыми элементами! Я попытался сослаться на другие ответы, как и предполагалось, я использовал getitems () в моем держателе bindview, но все равно ничего не происходит! поэтому мой вопрос: почему это происходит в моем случае, в какой части я делаю неправильно? может, потому что я создал специальный адаптер? Вот мой код: Класс адаптера:
class MainFolderImagesAdapter(list:ArrayList<String>, context: AppCompatActivity, bean:Bean, albumName: String, databaseHelper: DatabaseHelper): PagedListAdapter<String, MainFolderImagesAdapter.ViewHolder>(DIFF_CALLBACK) {
private var thumbPaths = list
private val tempThumbPath = ArrayList<String>()
private var context: AppCompatActivity? = context
private var albumName: String? = albumName
private val al_selected_photo = ArrayList<Int>()
private var mItemCLickAlbumImageListener: ItemCLickAlbumImageListener? = null
private var mDatabaseHelper: DatabaseHelper? = databaseHelper
private var mBean: Bean? = bean
internal var start = 0
internal var end = 20
internal var loop = 1
protected inner class LoadingVH(itemView: View) : ViewHolder(itemView) {
val mProgressBar: ProgressBar
init {
mProgressBar = itemView.findViewById(R.id.pbar)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
var viewHolder1: 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: ViewHolder, position: Int, payloads: List<Any>) {
super.onBindViewHolder(holder, position, payloads)
when (getItemViewType(position)) {
ITEM -> {
val movieVH = holder
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: ViewHolder, i: Int) {
holder1.setIsRecyclable(false)
when (getItemViewType(i)) {
ITEM -> {
val holder = holder1 as ViewHolder
val uniqueID: Int
if (Share.checkUserType(context)) {
uniqueID = mDatabaseHelper!!.getImagesUniqueID(albumName,
getOriginalFilename(getItem(i)), DatabaseHelper.IMAGES_TABLE)
} else {
uniqueID = mDatabaseHelper!!.getImagesUniqueIDGuest(albumName,
getOriginalFilename(getItem(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 {
Glide.with(context)
.load(ImageEncryptDecrypt.decrypt(context, getItem(i)))
.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);
val uniqueID1: Int
if (Share.checkUserType(context)) {
uniqueID1 = mDatabaseHelper!!.getImagesUniqueID(albumName,
getOriginalFilename(getItem(i)), DatabaseHelper.IMAGES_TABLE)
} else {
uniqueID1 = mDatabaseHelper!!.getImagesUniqueIDGuest(albumName,
getOriginalFilename(getItem(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
}
fun unSelectAll() {
for (i in al_selected_photo.indices) {
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()
}
private fun updateResultNew() {
Log.e("updateResultNew", "updateResultNew: start_end$start : $end")
for (i in start until end) {
if (i < tempThumbPath.size && tempThumbPath[i] != null) {
thumbPaths.add(tempThumbPath[i])
// notifyItemInserted(thumbPaths.size - 1)
(context as MainFolderImagesActivity).changeCount(thumbPaths.size)
start++
if (start == end) {
start = end
end = end + 20
loop++
val handler = Handler()
handler.postDelayed({ updateResultNew() }, 1000)
}
} else {
return
}
}
}
open 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")
}
}
companion object {
val DIFF_CALLBACK: DiffUtil.ItemCallback<String> = object : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
return true
}
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
return true
}
}
private var isLoadingAdded = false
// View Types
private val ITEM = 0
private val LOADING = 1
}
}
Вот мой класс источника данных:
inner class DataSource: PageKeyedDataSource<Int, String>(){
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, String>) {
val initialData = mImageItems.subList(0, params.requestedLoadSize)
callback.onResult(initialData, null, initialData.size)
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, String>) {
rcv_images.post(object:Runnable {
override fun run() {
val afterData = mImageItems.subList(params.key, params.requestedLoadSize)
val next = params.key + afterData.size
Log.i("key:" + afterData.size.toString(), "loadsize:" + next.toString())
callback.onResult(afterData, next)
}
})
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, String>) {
}
}
Вот как я устанавливаю конфигурацию:
val config: PagedList.Config = PagedList.Config.Builder()
.setInitialLoadSizeHint(30)
.setPageSize(30)
.build()
val pagedList = PagedList.Builder(DataSource(), config)
.setFetchExecutor(Executors.newSingleThreadExecutor())
.setNotifyExecutor(Executors.newSingleThreadExecutor())
.build()
mMainFolderImagesAdapter!!.submitList(pagedList)