滚动到最后一个位置时如何将项目添加到 PagingListAdpter

How to add item into PagingListAdpter when scroll to last position

当用户滚动到最后一个位置时,如何添加不同 ViewType 的新项目并在 recyclerView 上显示它?

我已经从 loadInitial 和 loadAfter 获取数据。 但是我想知道 API 发给我最后一个项目时如何添加新项目?

例如 API 发送数据大小 50 并且当用户滚动到位置 49 时 我需要将另一个是我的自定义 ViewType 添加到适配器中,大小将是 51 位置 50

从服务器加载 50 个项目后(可能在 20+20+10 的 3 次调用中)

只有 generate/fetch 个您希望在第 50 位之后显示的项目,

比 return 那些 generated/fetched 项通过调用:

'callback.onResult'

这是我的代码 它会为你工作

class FollowFeedPagedListAdapter(val context: Context, val itemClicked: (FollowFeedModel) -> Unit) : PagedListAdapter<FollowFeedModel, RecyclerView.ViewHolder>(DIFF_COMPARATOR) {


val TYPE_NORMAL = 1
val TYPE_LAST_POSITION = 2

companion object {
    private val DIFF_COMPARATOR = object : DiffUtil.ItemCallback<FollowFeedModel>() {
        override fun areItemsTheSame(oldItem: FollowFeedModel, newItem: FollowFeedModel): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: FollowFeedModel, newItem: FollowFeedModel): Boolean {
            return oldItem.id == newItem.id
        }
    }

    private var hasMore: Boolean = true

    @JvmStatic
    fun getHasMoreInstance() = hasMore

    @JvmStatic
    fun setHasMoreInstance(boolean: Boolean) {
        hasMore = boolean

    }
}

override fun getItemCount(): Int {
    val size = super.getItemCount()
    //เพิ่มอันสุดท้าย
    return size+1
}

override fun getItemViewType(position: Int): Int {
    if (position == itemCount - 1) {
        return TYPE_LAST_POSITION
    } else {
        return TYPE_NORMAL
    }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    when (viewType) {
        TYPE_NORMAL -> {
            val view = LayoutInflater.from(context).inflate(R.layout.row_summaries_layout_version2, parent, false)
            return SummariesModelViewHolder(view, itemClicked)
        }
        TYPE_LAST_POSITION -> {
            val view = LayoutInflater.from(context).inflate(R.layout.layout_no_more_follow_feed, parent, false)
            return NoMoreFollowFeedViewHolder(view)
        }
        else -> {
            val view = LayoutInflater.from(context).inflate(R.layout.layout_no_more_follow_feed, parent, false)
            return SummariesModelViewHolder(view, itemClicked)
        }
    }
}


override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

    when (holder.itemViewType) {
        TYPE_NORMAL -> {
            val holder = holder as SummariesModelViewHolder
            holder.binding(getItem(position))
        }
        TYPE_LAST_POSITION -> {
            val holder = holder as NoMoreFollowFeedViewHolder
        }
    }
}