最近在研究安卓的Kotlin,碰到的問題是:首頁是一個(gè)多列表頁面,見下圖
頂部接口分類接口大于三個(gè),每個(gè)分類的列表含有大于三個(gè)模塊(例如:動(dòng)作片,喜劇片,科幻片...),這樣算起來了啟動(dòng)加載的數(shù)據(jù)接口,大概有六個(gè),甚至更多.... 這種情況一次性請(qǐng)求 顯然不太科學(xué),一是接口返回需要時(shí)間,增加啟動(dòng)時(shí)間,二是其中一個(gè)接口請(qǐng)求失敗,無法及時(shí)刷新數(shù)據(jù).所以就想到當(dāng)前item出現(xiàn)在屏幕中的時(shí)候在加載進(jìn)行刷新.這樣請(qǐng)求接口就減少了很多.如果用戶不滑到底部,那么底部的item數(shù)據(jù)就不用加載了.也減少了不必要的數(shù)據(jù)請(qǐng)求.
代碼如下:
view!!.home_fr_list.addOnScrollListener(object: RecyclerView.OnScrollListener(){
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
Log.e("scrole","調(diào)用了ScrollStateChanged")
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val lastPosition = linerlayout.findLastVisibleItemPosition()
//:找到最后一個(gè)顯示的
val currentTypeM = homeList[lastPosition]
//如果當(dāng)前數(shù)組為空 并且不再 加載中 那就去請(qǐng)求數(shù)據(jù)
if (!currentTypeM.videList.isNotEmpty() && !currentTypeM.isLoading){
currentTypeM.isLoading = true
Log.e("滾動(dòng):RecyclerView","${currentTypeM.modeModel.resource_type_name}")
paramsM = ParamsModel(mod_id = CurrentCatorM.mod_id,resource_type_id = currentTypeM.modeModel.resource_type_id)
getPersenter()!!.getCurrentCatorgryVideoListModel(paramsM,lastPosition)
}
}
})
在監(jiān)聽事件里面 判斷當(dāng)前item 數(shù)據(jù)源是否有數(shù)據(jù),如果為空就帶上當(dāng)前Position和參數(shù)去請(qǐng)求數(shù)據(jù),以便數(shù)據(jù)請(qǐng)求回來能夠找到刷新位置.然后在數(shù)據(jù)賦值哪里:
override fun <T> setData(data: T, identi: String,currentPostion:Int) {
//:分塊數(shù)據(jù)
if (identi == "banner") {
bannerList = data as MutableList<BannerModel>
val refreshData = homeList[0]
refreshData.bannerList = bannerList
//:賦值 顯示數(shù)據(jù)
homeAdpter.notifyItemChanged(0)
}
//:接受數(shù)據(jù)
if (identi == "list"){
val listModel = data as HomeListModel
val refreshData = homeList[currentPostion]
refreshData.videList = listModel.data
homeAdpter.notifyItemChanged(currentPostion)
}
}
使用notifyItemChanged 來刷新當(dāng)前請(qǐng)求位置的數(shù)據(jù).這樣就完成了首頁數(shù)據(jù)懶加載的操作.
目前數(shù)據(jù)能夠正常加載啦~~~
遺留問題:
就是第一屏數(shù)據(jù)item 大于兩個(gè) ,那么第一個(gè)和和第二個(gè)都不會(huì)取請(qǐng)求數(shù)據(jù),這個(gè)通過 把findLastVisibleItemPosition 換成findFirstVisibleItemPosition 可以解決 總是加載屏幕中的加載第一個(gè)item.這樣也會(huì)有個(gè)問題就是,滑到底部的話,如果存在大于兩個(gè)item,最后一個(gè)item數(shù)據(jù)不會(huì)被夾在.
問題正在解決中.........
如果你有很好的建議歡迎指正!隨時(shí)在線!!!!!
補(bǔ)充數(shù)據(jù)加載方式
val firstPosition = linerlayout.findLastVisibleItemPosition()
val lastPosition = linerlayout.lastLastVisibleItemPosition()
visibleItemsArr = firstPosition - lastPosition ;得到可見屏幕內(nèi)可見items下標(biāo)數(shù)組
然后 for循環(huán)遍歷請(qǐng)求屏幕內(nèi)的可見模塊的數(shù)據(jù).