Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Listview分批加載+自動加載(附源碼下載)

android Listview分批加載+自動加載(附源碼下載)

編輯:關於Android編程

直接上代碼,代碼有注釋:

public class TestForListviewActivity extends Activity implements
		OnScrollListener {
	private ListView mListview = null;
	private View mFooterView;
	private PaginationAdapter mAdapter;
	private Handler handler=new Handler();
	private boolean isLoading;//表示是否正在加載
	private final int MAX_COUNT=35;//表示服務器上總共有MAX_COUNT條數據
	private final int EACH_COUNT=10;//表示每次加載的條數
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mFooterView = getLayoutInflater().inflate(R.layout.loadmore, null);
		mListview = (ListView) findViewById(R.id.listview);
		mListview.addFooterView(mFooterView);// 設置列表底部視圖
		
		List news=new ArrayList();
		mAdapter = new PaginationAdapter(news);;
		mListview.setAdapter(mAdapter);
		//設置setOnScrollListener會自動調用onscroll方法。
		mListview.setOnScrollListener(this);

	}

	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
		if (firstVisibleItem+visibleItemCount==totalItemCount&&!isLoading) {
			//isLoading = true 表示正在加載,加載完畢設置isLoading =false;
			isLoading = true;
			//如果服務端還有數據,則繼續加載更多,否則隱藏底部的加載更多
			if (totalItemCount<=MAX_COUNT) {
				//等待2秒之後才加載,模擬網絡等待時間為2s
				handler.postDelayed(new Runnable() {
					
					public void run() {
						loadMoreData();
					}
				},2000);
			}else{
				if (mListview.getFooterViewsCount()!=0) {
					mListview.removeFooterView(mFooterView);
				}
			}
			
		}

	}

	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		Log.i("onScrollStateChanged", arg1+"");
	}
	
	private void loadMoreData(){
		int count = mAdapter.getCount();
		for (int i = 0; i < EACH_COUNT; i++) {
			if (count+i newsItems;

		public PaginationAdapter(List newsitems) {
			this.newsItems = newsitems;
		}

		public int getCount() {
			return newsItems==null?0:newsItems.size();
		}

		public Object getItem(int position) {
			return newsItems.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public void addNewsItem(News newsitem) {
			newsItems.add(newsitem);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.list_item,
						null);
			}
			// 新聞標題
			TextView tvTitle = (TextView) convertView
					.findViewById(R.id.newstitle);
			tvTitle.setText(newsItems.get(position).getTitle());
			// 新聞內容
			TextView tvContent = (TextView) convertView
					.findViewById(R.id.newscontent);
			tvContent.setText(newsItems.get(position).getContent());

			return convertView;
		}
	}
}


demo源碼下載:源碼下載


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved