1

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

在此处输入图像描述

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

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

4

2 回答 2

0

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

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
        }
    }
}
于 2019-08-31T08:40:06.610 回答
0

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

只需生成/获取您想要在第 50 位之后显示的项目,

通过调用返回那些生成/获取的项目:

'callback.onResult'

于 2019-08-30T17:47:13.463 回答