在listview中,實現_分頁加載_異步加載

public void onScroll(AbsListView view, int firstVisibleItem,

        int visibleItemCount, int totalItemCount) {

    // 若已經顯示到了最後一條記錄,則嘗試繼續更新記錄。

    if(firstVisibleItem + visibleItemCount == totalItemCount){

        // 計算下一頁的頁號。

        int nextPage = totalItemCount/pageSize + 1 ;

        if(nextPage != currentPage){

// 更新當前頁,以免開啓第二個線程,重複加載數據。

// nextPage是根據totalItemCount來計算的,若第一個線程沒有加載完畢,totalItemCount的值是不會改變的,因此當用戶再次滑動滾動條到末尾時,由於totalItemCount的值沒更改,所以nextPage的值也沒有變,這樣就保證了數據不會被加載兩遍。

            currentPage = nextPage;

            // 開始加載數據。

            new MyAsyncTask().execute();

        }

    }

}

語句解釋:

|-  爲了頁面清晰,本範例僅僅將核心代碼列出來。

|-  變量currentPage代表當前已經加載了多少頁的數據。默認值爲0 。

|-  變量nextPage代表將要加載哪一頁的數據。變量pageSize代表每頁包含多少個Item。

 

範例AsyncTask。

private final class MyAsyncTask extends AsyncTask<Object, Object, Object>{

        private View footView;

        protected void onPreExecute() {

// 下載之前先向ListView中添加一個表尾。

            footView = inflater.inflate(R.layout.list_foot, null);

            listView.addFooterView(footView);

        }

        protected Object doInBackground(Object... params) {

            IPersonDAO dao = new PersonDAOImpl(getApplicationContext());

            List<Person> list = dao.findAll(currentPage, pageSize);

            if(list.size()>0){

                myAdapter.setPersons(list);

            }

            this.publishProgress(list.size()>0);

            return null;

        }

        protected void onProgressUpdate(Object... values) {

// 下載之後將表尾刪除。

            listView.removeFooterView(footView);

            if((Boolean)values[0]){ // 只有成功獲取了數據之後,纔會通知ListViw更新。

                myAdapter.notifyDataSetChanged();

            }else{

Toast.makeText(Main.this,"數據加載完成",Toast.long());

        }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章