如何插入ProgressBar以在Recycler View中加载更多项目?

时间:2019-11-26 10:49:20

标签: android android-layout android-recyclerview recycler-adapter

每个API调用可获得50个项目,并将其插入RecyclerView中。滚动到末尾时,我在最后一个现有的ProgressBar内添加一个ViewHolder并显示它,而不是为ViewHolder使用单独的ProgressBar。但是存在一些性能问题。有人可以告诉我我的方法是否正确吗?如果有人可以建议我采取正确的方法,我将不胜感激

2 个答案:

答案 0 :(得分:0)

最后一次要在recyler视图中显示加载程序,您只需为加载程序创建另一个视图项并重写Recycler View的getItemViewType方法,然后根据您的情况传递此进度条视图ID。

@Override
public int getItemViewType(int position) {
    if (TextUtils.isEmpty(YOUR_LIST(position))) {
        return PROGRESS_VIEW;
    } else {
        return ITEM_VIEW;
    }
}

答案 1 :(得分:0)

这是Adapter类

  class AdapterClass(private var mList: MutableList<Any>?,
                     var  mContext: Context
                    ) : RecyclerView.Adapter< RecyclerView.ViewHolder>() {

private val DATA = 1
private val LOADER = 2

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return if (viewType == DATA) {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.view, parent, false)
        Items(view)
    } else {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_loadmore, parent, false)
        ViewHolderLoader(view)
    }
}

override fun getItemCount(): Int {
    return mList?.size?:0
}


override fun getItemViewType(position: Int): Int {
    return when {
        mList?.get(position) is DataItem -> DATA
        mList?.get(position) is Loader -> LOADER
        else -> DATA
    }
}



override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
    if (holder?.itemViewType == DATA) {
        val viewHolder = holder as AdapterClass.Items
        val dataItem = mList?.get(position) as DataItem

        viewHolder.bindData(dataItem)
    }
}

inner class Items(itemView: View?) : RecyclerView.ViewHolder(itemView) {

    @SuppressLint("SetTextI18n")
    fun bindData(data: DataItem?) {
}
inner class ViewHolderLoader(itemView: View) : RecyclerView.ViewHolder(itemView)

}