ListView就是可以顯示一行行Item的控制元件,有時候資料非常多,通常需要分頁顯示,但為了減少使用者的輸入,我們可以動態更新ListView,把下一頁要顯示的資料的新增到當前ListView中。
先看看效果:
需要注意的是在什麼時候去更新資料 ,listVIew的setOnScrollListener監聽是否滾到了最後一條記錄,
取到的資料加到list中,最後記得呼叫adapter的notifyDataSetChanged,通知listview改變。
不廢話,上程式碼。
主檔案:
import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import android.widget.Toast; public class ListViewActivity extends Activity { private ListView listView; //定義介面卡 private ListItemAdapter listadpter; //定義每一頁顯示行數 private int VIEW_COUNT = 20; //定義的頁數 private int index = 0; //當前頁 private int currentPage = 1; //所以資料的條數 private int totalCount; //每次取的資料,只要最後一次可能不一樣。 private int maxResult; //泛型集合ArrayList private ArrayList<Students> arrayList = new ArrayList<Students>(); //資料操作的dao類 StudentsDAO dao = new StudentsDAO(ListViewActivity.this); //實體bean Students students = new Students(); // 標記:上次的ID private boolean isUpdating = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //初始化介面 initView(); //插入100條記錄。 dao.insert(); totalCount = dao.getCount(); maxResult = getMaxResult(); //呼叫dao裡面的selectAll()方法 arrayList = dao.getAllItems(index, maxResult); //例項化介面卡 System.out.println("arrlist-->"+arrayList.size()); listadpter = new ListItemAdapter(ListViewActivity.this,arrayList); //填充介面卡 listView.setAdapter(listadpter); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(firstVisibleItem + visibleItemCount == totalItemCount && !isUpdating){ if(totalItemCount<totalCount){ //防止最後一次取資料進入死迴圈。 Toast.makeText(ListViewActivity.this, "正在取第"+(++currentPage)+"的資料", Toast.LENGTH_LONG).show(); AsyncUpdateDatasTask asyncUpdateWeiBoDatasTask = new AsyncUpdateDatasTask(); asyncUpdateWeiBoDatasTask.execute(); } System.out.println("begin update-------------"); } } }); } //初始化介面方法 private void initView() { // TODO Auto-generated method stub listView = (ListView) findViewById(R.id.list); } class AsyncUpdateDatasTask extends AsyncTask<Void, Void, List<Students>> { @Override protected List<Students> doInBackground(Void... params) { // TODO Auto-generated method stub isUpdating = true; index += VIEW_COUNT; List<Students> list =new ArrayList<Students>(); list = dao.getAllItems(index, maxResult); return list; } @Override protected void onPostExecute(List<Students> result) { // TODO Auto-generated method stub super.onPostExecute(result); arrayList.addAll(result); listadpter.notifyDataSetChanged(); isUpdating = false; System.out.println("end update--------------"); } } private int getMaxResult(){ int totalPage = (totalCount+VIEW_COUNT-1)/VIEW_COUNT; return totalCount-(totalPage-1)*VIEW_COUNT; } }資料庫Dao檔案:package com.shao.list; import java.util.ArrayList; import java.util.Random; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class StudentsDAO extends SQLiteOpenHelper { private final static String AUDIODATABASE_NAME = "student.db"; private final static String TABLE = "student"; private final static String COLUM_ID = "id"; private final static String COLUM_NAME = "name"; private final static String COLUM_AGE = "age"; private final static int DATABASE_VERSION = 1; private long row; private ArrayList<Students> arrayList; public StudentsDAO(Context context) { super(context, AUDIODATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String sql = "CREATE TABLE " + TABLE + " (" + COLUM_ID + " INTEGER primary key autoincrement, " + " " + COLUM_NAME + " text, " + " " + COLUM_AGE + " int)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub String sql = "DROP TABLE IF EXISTS " + TABLE; db.execSQL(sql); } public long insert() { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); Random random = new Random(); for(int i=1;i<=100;i++) { cv.put(COLUM_ID, i); cv.put(COLUM_NAME, "name"+String.valueOf(i)); cv.put(COLUM_AGE, random.nextInt(100)); row = db.insert(TABLE, null, cv); } db.close(); return row; } //查詢記錄的總數 public int getCount() { SQLiteDatabase db = getWritableDatabase(); String sql = "select count(*) from '"+TABLE+"'"; Cursor c = db.rawQuery(sql, null); c.moveToFirst(); int length = c.getInt(0); c.close(); db.close(); // System.out.println("length-->"+length); return length; } public ArrayList<Students> getAllItems(int firstResult, int maxResult) { arrayList=new ArrayList<Students>(); SQLiteDatabase db = getWritableDatabase(); String sql = "select * from '"+TABLE+"' limit ?,?"; Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(firstResult), String.valueOf(maxResult)}); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { Students students=new Students(); students.setId(cursor.getInt(0)); students.setName(cursor.getString(1)); students.setAge(cursor.getInt(2)); arrayList.add(students); } cursor.close(); db.close(); return arrayList; } public ArrayList<Students> selectAll() { arrayList=new ArrayList<Students>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.query(TABLE, null, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { Students students=new Students(); students.setId(cursor.getInt(0)); students.setName(cursor.getString(1)); students.setAge(cursor.getInt(2)); arrayList.add(students); } cursor.close(); db.close(); return arrayList; } }