引入依賴:
//上拉刷新下拉加載:
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0'
布局xml文件
<com.scwang.smartrefresh.layout.SmartRefreshLayout
android:id="@+id/refreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srlEnableRefresh="true">
<-刷新的頭部->
<com.scwang.smartrefresh.layout.header.ClassicsHeader
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.hjq.widget.layout.HintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/credit_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp" />
</com.hjq.widget.layout.HintLayout>
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
在activity中
//定義的bean
private var listbean: ArrayList<Bean>? = null
//adapter
lateinit var adapter: MyAdapter
//分頁 從1開始
var pageNow = 1
//是否有數(shù)據(jù)可繼續(xù)上拉加載
var isEnd = false
//上拉下拉刷新事件
refreshLayout_credit.setOnRefreshListener { refreshlayout ->
refreshlayout.finishRefresh(2000/*,false*/)//傳入false表示刷新失敗
pageNow = 1
isEnd = false
listbean!!.clear()
adapter.notifyDataSetChanged()
initData()//請求數(shù)據(jù)的方法
}
refreshLayout_credit.setOnLoadMoreListener { refreshlayout ->
refreshlayout.finishLoadMore(2000/*,false*/)//傳入false表示加載失敗
if (isEnd) {
ToastUtils.showShort("無更多數(shù)據(jù)习寸!")
refreshLayout_credit.finishRefresh()//停止刷新
} else {
initData()//請求數(shù)據(jù)的方法
}
}
/**
* 請求列表
*/
private fun initData() {
showLoading()//加載中的彈窗
//請求方法都不一樣,我只發(fā)一下請求成功之后的解析吧
//我這里解析用的阿里的fastjson:
// implementation 'com.alibaba:fastjson:1.1.71.android'
//括號(hào)第一個(gè)是返回的數(shù)據(jù)肴裙,第二個(gè)是封裝的bean
var list = JSON.parseArray(apiResult.data,Bean::class.java)
//如果數(shù)據(jù)小于每頁的數(shù)量 不在加載更多
if (list.size >= 10) { //分頁的數(shù)量 如果后臺(tái)返回的list長度大于10爵政,分頁就+1
pageNow++
} else {
isEnd = true
}
listbean!!.addAll(list)
adapter.setNewData(listbean)//adapter設(shè)置數(shù)據(jù)
adapter.notifyDataSetChanged()//刷新adapter
refreshLayout_credit.finishRefresh() //結(jié)束刷新
showComplete() //結(jié)束加載
}
else -> {
showComplete()//結(jié)束加載
//頁面如果為1佣谐,顯示空數(shù)據(jù)布局锐极,否則彈出toast
if (pageNow == 1) {
//數(shù)據(jù)為空的提示布局
showEmpty()
} else {
toast("后臺(tái)返回的錯(cuò)誤信息")
}
}
Adapter
//萬能適配器 implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.47'
class MyAdapter(layoutResId: Int, data: List<Bean?>?) :
BaseQuickAdapter<Bean, BaseViewHolder>(layoutResId, data) {
override fun convert(helper: BaseViewHolder, item: Bean) {
//這里就不多說了煤痕,就一個(gè)設(shè)置數(shù)據(jù)的adapter而已
helper.setText(R.id.item, item.mark)
.setText(R.id.tv_number, item.score)
}
}