Android安卓中分页加载不仅仅为了美观,不仅仅为了用户体验效果,其实……同时也是为了节约内存,内存啊!亲
那么简单说一下怎么实现listview分页加载:
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
}
};