listview分頁載入問題
阿新 • • 發佈:2019-01-09
1.在listview初始化的時候加個footview,並初始化相關變數以及要設定listview的OnScrollListener:
listview = (ListView) layoutMain.findViewById(R.id.vidoe_list);
layoutFooter = (RelativeLayout) mLayoutInflater.inflate(
R.layout.contact_list_footer, null);
listview.addFooterView(layoutFooter);
adapter = new VideoListAdapter();
listview.setAdapter(adapter);
listview.setOnItemClickListener(mItemClickListener);
listview.setOnScrollListener(mHLOnScrollListener);
2.載入資料:載入資料的時候最好用一個執行緒來執行載入過程,完了之後就用handler發個訊息出來。這裡要控制這個執行緒的
生命週期,假如執行緒已經啟動並且還沒跑完,就先不要再啟動,等上一次跑完再start一個執行緒
private Thread threadLoadHLData;
List<VidoeDetailInfoItem> listVideoInfo = new ArrayList<VidoeDetailInfoItem>();// 資料列表
List data ;
private void onLoadData(final String url, final String pageName) {
if (threadLoadHLData == null || !threadLoadHLData.isAlive()) {//檢測執行緒狀態
threadLoadHLData = new Thread() {
public void run() {
Looper.prepare();
try {
data = VideoDownloadClient.requestPageData(
VideoListLayoutManager.this.ctx, url,
PageParserFactory.getParser(parserType), pageName);
//sleep(200);
if(null != data){
HLhandler.obtainMessage(1).sendToTarget();
}else{
HLhandler.obtainMessage(2).sendToTarget();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IOException", e.getMessage());
HLhandler.obtainMessage(2).sendToTarget();
}
}
};
threadLoadHLData.start();
}
}
3.在OnScrollListener的實現方法中檢測是不是已經滑動到最後一個:
OnScrollListener mHLOnScrollListener = new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (firstVisibleItem + visibleItemCount == totalItemCount) {//判斷是不是最後一個
// 開執行緒去下載網路資料
if (threadLoadHLData == null || !threadLoadHLData.isAlive()) {
onLoadData(url );//這裡的載入資料跟開始初始化時一樣的
//if (pageHLIndex < 82) {
pageHLIndex++;
//}
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
};