Endless RecyclerView with ProgressBar for pagination

前端 未结 9 2176
庸人自扰
庸人自扰 2020-11-27 12:51

I am using a RecyclerView and fetching objects from an API in batches of ten. For pagination, I use EndlessRecyclerOnScrollListener.

It\'s all working properly. Now

9条回答
  •  失恋的感觉
    2020-11-27 13:03

    here is my workaround without adding a fake item (in Kotlin but simple):

    in your adapter add:

    private var isLoading = false
    private val VIEWTYPE_FORECAST = 1
    private val VIEWTYPE_PROGRESS = 2
    
    override fun getItemCount(): Int {
        if (isLoading)
            return items.size + 1
        else
            return items.size
    }
    
    override fun getItemViewType(position: Int): Int {
        if (position == items.size - 1 && isLoading)
            return VIEWTYPE_PROGRESS
        else
            return VIEWTYPE_FORECAST
    }
    
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == VIEWTYPE_FORECAST)
            return ForecastHolder(LayoutInflater.from(context).inflate(R.layout.item_forecast, parent, false))
        else
            return ProgressHolder(LayoutInflater.from(context).inflate(R.layout.item_progress, parent, false))
    }
    
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        if (holder is ForecastHolder) {
            //init your item
        }
    }
    
    public fun showProgress() {
        isLoading = true
    }
    
    
    public fun hideProgress() {
        isLoading = false
    }
    

    now you can easily call showProgress() before API call. and hideProgress() after API call was done.

提交回复
热议问题