android實現listview分頁的方法_Android

來源:互聯網
上載者:User

本文執行個體講述了android實現listview分頁的方法。分享給大家供大家參考。具體分析如下:

最近做了下listview的分頁,跟WEB上的分頁是一個意思,需要那幾個分頁參數,不同的是sqlite中分頁的查詢語句,簡便的方法需要用Limit,Offset關鍵字,前者是查詢每頁展示的記錄數,後者是越過多少記錄數,說得明白點就是忽略前面多少行記錄之後,取多少行記錄

我分頁採用了一個重要的類Page,通過封裝Page類,做為參數傳遞進來,返回出去也是個Page對象

import java.util.Collections; import java.util.List; /**  * 注意所有序號從1開始.  *  * @param <T> Page中記錄的類型.  *  */ public class Page<T> {   //-- 公開變數 --//   public static final String ASC = "asc";   public static final String DESC = "desc";   //-- 分頁參數 --//   protected int pageNo = 0;// 當前頁號<跟取資料的方式有關係>   protected int pageSize = 1;// 每頁顯示的記錄數   protected String orderBy = null;   protected String order = null;   protected boolean autoCount = true;   //-- 返回結果 --//   protected List<T> result = Collections.emptyList();   protected long totalCount = -1;// 總記錄數   //-- 建構函式 --//   public Page() {   }   public Page(final int pageSize) {     setPageSize(pageSize);   }   public Page(final int pageSize, final boolean autoCount) {     setPageSize(pageSize);     setAutoCount(autoCount);   }   //-- 訪問查詢參數函數 --//   /**    * 獲得當前頁的頁號,序號從0開始,預設為0.    */   public int getPageNo() {     return pageNo;   }   /**    * 設定當前頁的頁號,序號從0開始,低於0時自動調整為0.    */   public void setPageNo(final int pageNo) {     this.pageNo = pageNo;     if (pageNo < 0) {       this.pageNo = 0;     }   }   /**    * 獲得每頁的記錄數量,預設為1.    */   public int getPageSize() {     return pageSize;   }   /**    * 設定每頁的記錄數量,低於0時自動調整為0.    */   public void setPageSize(final int pageSize) {     this.pageSize = pageSize;     if (pageSize < 0) {       this.pageSize = 0;     }   }   /**    * 根據pageNo和pageSize計算當前頁第一條記錄在總結果集中的位置,序號從0開始.    */   public int getFirst() {     return (pageNo * pageSize) + 1;   }   /**    * 獲得排序欄位,無預設值.多個排序欄位時用','分隔.    */   public String getOrderBy() {     return orderBy;   }   /**    * 設定排序欄位,多個排序欄位時用','分隔.    */   public void setOrderBy(final String orderBy) {     this.orderBy = orderBy;   }   /**    * 獲得排序方向.    */   public String getOrder() {     return order;   }   /**    * 設定排序方式.    *    * @param order 可選值為desc或asc    */   public void setOrder(String order) {     this.order = order;   }   /**    * 查詢對象時是否自動另外執行count查詢擷取總記錄數, 預設為false.    */   public boolean isAutoCount() {     return autoCount;   }   /**    * 查詢對象時是否自動另外執行count查詢擷取總記錄數.    */   public void setAutoCount(final boolean autoCount) {     this.autoCount = autoCount;   }   //-- 訪問查詢結果函數 --//   /**    * 取得頁內的記錄列表.    */   public List<T> getResult() {     return result;   }   /**    * 設定頁內的記錄列表.    */   public void setResult(final List<T> result) {     this.result = result;   }   /**    * 取得總記錄數, 預設值為-1.    */   public long getTotalCount() {     return totalCount;   }   /**    * 設定總記錄數.    */   public void setTotalCount(final long totalCount) {     this.totalCount = totalCount;   }   /**    * 根據pageSize與totalCount計算總頁數, 預設值為-1.    */   public long getTotalPages() {     if (totalCount < 0)       return -1;     long count = totalCount / pageSize;     if (totalCount % pageSize > 0) {       count++;     }     return count;   }   /**    * 是否還有下一頁.    */   public boolean isHasNext() {     return (pageNo + 1 < getTotalPages());   }   /**    * 取得下頁的頁號, 序號從0開始.    * 當前頁為尾頁時仍返回尾頁序號.    */   public int getNextPage() {     if (isHasNext())       return pageNo + 1;     else       return pageNo;   }   /**    * 是否還有上一頁.    */   public boolean isHasPre() {     return (pageNo - 1 >= 0);   }   /**    * 取得上頁的頁號, 序號從1開始.    * 當前頁為首頁時返回首頁序號.    */   public int getPrePage() {     if (isHasPre())       return pageNo - 1;     else       return pageNo;   } }

下面是封裝的POJO對象,介面listview的item展示就是靠它

public class Record {   private Integer rId;   private String fromUser;   private String toUser;   private String content;   private String rTime;   private Integer isReaded;   public Integer getrId() {     return rId;   }   public void setrId(Integer rId) {     this.rId = rId;   }   public String getFromUser() {     return fromUser;   }   public void setFromUser(String fromUser) {     this.fromUser = fromUser;   }   public String getToUser() {     return toUser;   }   public void setToUser(String toUser) {     this.toUser = toUser;   }   public String getContent() {     return content;   }   public void setContent(String content) {     this.content = content;   }   public String getrTime() {     return rTime;   }   public void setrTime(String rTime) {     this.rTime = rTime;   }   public Integer getIsReaded() {     return isReaded;   }   public void setIsReaded(Integer isReaded) {     this.isReaded = isReaded;   }}

好吧,來看下DAO類裡的重要方法同樣是Page對象,在DAO類裡做的操作就是對總記錄數和結果list進行賦值

public Page<Record> getRecordPage(Page<Record> page, String loginName,       String contactName) {     int pageSize = page.getPageSize();     int pageNo = page.getPageNo();     String sql = "select * from "         + ContactsManagerDbAdapter.TABLENAME_RECORD         + " where (fromUser = ? and toUser = ?) or (fromUser = ? and toUser = ?)"         + " Limit " + String.valueOf(pageSize) + " Offset "         + String.valueOf(pageNo * pageSize);     String[] selectionArgs = { loginName, contactName, contactName,         loginName };     Cursor cursor = mSQLiteDatabaseWritable.rawQuery(sql, selectionArgs);     List<Record> result = new ArrayList<Record>();     for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){       Record record = new Record();       record.setrId(cursor.getInt(0));       record.setFromUser(cursor.getString(1));       record.setToUser(cursor.getString(2));       record.setContent(cursor.getString(3));       record.setrTime(cursor.getString(4));       record.setIsReaded(cursor.getInt(5));       result.add(record);     }     page.setTotalCount(getRowCount(loginName, contactName));     page.setResult(result);     cursor.close();     return page; } /** * 總記錄數 */ public int getRowCount(String loginName, String contactName){     String sql = "select * from "       + ContactsManagerDbAdapter.TABLENAME_RECORD       + " where (fromUser = ? and toUser = ?) or (fromUser = ? and toUser = ?)";     String[] selectionArgs = { loginName, contactName, contactName,        loginName };     Cursor cursor = mSQLiteDatabaseWritable.rawQuery(sql, selectionArgs);     int count = cursor.getCount();     cursor.close();     return count; } 

關於listview的展示和自訂配接器,在此不提起,總之介面上上一頁和下一頁按鈕的點擊事件需要重新整理listview

public class ChatHistory extends Activity {   ListView historyView;   Button prevPageBtn;   Button nextPageBtn;   TextView historyPageTv;   Button backChatsHistoryBtn;   Button deleteHistoryBtn;   List<Record> historyRecordList;    Page<Record> page;   String loginName;   String contactName;   ChatHistoryService chatHistoryService;   ContactsManagerDbAdapter dbAdapter;   private BaseAdapter adapter;   private static final int STATUS_CHANGE = 0;   private Handler mHandler;   @Override   protected void onCreate(Bundle savedInstanceState) {     // TODO Auto-generated method stub     super.onCreate(savedInstanceState);     setContentView(R.layout.chats_history);     historyView = (ListView) findViewById(android.R.id.list);     prevPageBtn = (Button) findViewById(R.id.chat_prev_page);     nextPageBtn = (Button) findViewById(R.id.chat_next_page);     historyPageTv = (TextView) findViewById(R.id.history_page);     backChatsHistoryBtn = (Button) findViewById(R.id.back_chats_history);     deleteHistoryBtn = (Button) findViewById(R.id.delete_history);     SharedPreferences sharedata = ChatHistory.this.getSharedPreferences("data", 0);     loginName = sharedata.getString("loginName", "");     contactName = getIntent().getStringExtra("contactName");     dbAdapter = new ContactsManagerDbAdapter(getApplicationContext());     dbAdapter.open();     chatHistoryService = new ChatHistoryService(ChatHistory.this);    page = new Page<Record>();     page.setPageSize(8);     page = chatHistoryService.getHistoryPage(page, loginName, contactName, dbAdapter);     historyRecordList = page.getResult();     updateTextView();     prevPageBtn.setOnClickListener(prevPageButtonListener);     nextPageBtn.setOnClickListener(nextPageButtonListener);     backChatsHistoryBtn.setOnClickListener(backButtonListener);     deleteHistoryBtn.setOnClickListener(deleteHistoryButtonListener);     adapter = new HistoryListAdapter(ChatHistory.this);     historyView.setAdapter(adapter);     mHandler = new Handler(){         public void handleMessage(Message msg) {           switch(msg.what){           case STATUS_CHANGE:             // 處理UI更新等操作             updateUI();           }        };     };   }   private void updateUI() {     //詳細的更新     adapter.notifyDataSetChanged();// 更新ListView     updateTextView();   }   /**    * 更新頁碼    */   private void updateTextView(){        if(historyRecordList.size() == 0){       historyPageTv.setText(0 + "/" + 0);     } else{       historyPageTv.setText(page.getPageNo() + 1 + "/" + page.getTotalPages());     }   }   public class HistoryListAdapter extends BaseAdapter{     private class RecentViewHolder {       TextView sender_context;       TextView rTime;     }     Context context;     LayoutInflater mInflater;     public HistoryListAdapter(Context context){       this.context = context;       mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);     }     @Override     public int getCount() {       // TODO Auto-generated method stub       return historyRecordList.size();     }     @Override     public Object getItem(int position) {       // TODO Auto-generated method stub       return historyRecordList.get(position);     }     @Override     public long getItemId(int position) {       // TODO Auto-generated method stub       return position;     }     @Override     public View getView(int position, View convertView, ViewGroup parent) {       // TODO Auto-generated method stub       RecentViewHolder holder;       if (convertView == null) {         convertView = mInflater.inflate(R.layout.message_layout, null);         holder = new RecentViewHolder();         holder.sender_context = (TextView) convertView             .findViewById(R.id.message_view_sender_content);        holder.rTime = (TextView) convertView             .findViewById(R.id.message_view_timestamp);         convertView.setTag(holder);       } else {         holder = (RecentViewHolder) convertView.getTag();       }       Record record = historyRecordList.get(position);       if (record != null) {         holder.sender_context.setText(record.getFromUser() + ":" + record.getContent());         holder.rTime.setText(record.getrTime());       }       return convertView;     }   }   /**    * 上一頁按鈕的監聽事件    */   OnClickListener prevPageButtonListener = new OnClickListener(){     @Override     public void onClick(View v) {       // TODO Auto-generated method stub       if(page.isHasPre()){         page.setPageNo(page.getPageNo() - 1);         historyRecordList = chatHistoryService.getHistoryPage(page, loginName, contactName, dbAdapter).getResult();         Message msg = new Message();         msg.what = STATUS_CHANGE;         mHandler.sendMessage(msg);// 向Handler發送訊息,更新UI       }     }   };   /**    * 下一頁按鈕的監聽事件    */   OnClickListener nextPageButtonListener = new OnClickListener(){     @Override     public void onClick(View v) {       // TODO Auto-generated method stub       if(page.isHasNext()){         page.setPageNo(page.getPageNo() + 1);         historyRecordList = chatHistoryService.getHistoryPage(page, loginName, contactName, dbAdapter).getResult();         Message msg = new Message();         msg.what = STATUS_CHANGE;         mHandler.sendMessage(msg);// 向Handler發送訊息,更新UI       }     }   };   /**    * 刪除記錄按鈕監聽器    */   OnClickListener deleteHistoryButtonListener = new OnClickListener() {     @Override     public void onClick(View v) {       // TODO Auto-generated method stub          }   };   /** 退出聊天介面監聽器 */   OnClickListener backButtonListener = new OnClickListener() {     @Override     public void onClick(View v) {       // TODO Auto-generated method stub       // 返回到聊天介面       finish();       dbAdapter.close();     }   };   @Override   public boolean onKeyDown(int keyCode, KeyEvent event) {     // 按下鍵盤上返回按鈕     if (keyCode == KeyEvent.KEYCODE_BACK) {       finish();       dbAdapter.close();       return true;     } else {       return super.onKeyDown(keyCode, event);     }  }}

上一頁,下一頁所做的操作也就是在判斷是否有上一頁和下一頁的情況下對頁號pageNo的加減操作
最後寫上ChatHistoryService.java總覺得是多餘的

public class ChatHistoryService {   Context context;   public ChatHistoryService(Context context) {     this.context = context;   }   public Page<Record> getHistoryPage(Page<Record> page, String loginName,       String contactName, ContactsManagerDbAdapter dbAdapter) {     RecordDao recordDao = new RecordDao(dbAdapter);     return recordDao.getRecordPage(page, loginName, contactName);   }   public int deleteHistory(String loginName,       String contactName, ContactsManagerDbAdapter dbAdapter){     RecordDao recordDao = new RecordDao(dbAdapter);     return recordDao.deleteHistoryRecord(loginName, contactName);   } } 

順帶放上XML布局檔案吧
chats_history.xml

<?xml version="1.0" encoding="UTF-8"?> <!-- 與好友聊天視窗.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical" android:layout_width="fill_parent"   android:layout_height="fill_parent" android:background="@color/white">   <ListView android:id="@android:id/list" android:layout_width="fill_parent"     android:layout_height="200dip" android:layout_weight="1"     android:transcriptMode="normal" android:fadingEdge="none"     android:padding="4px" android:fastScrollEnabled="true"     android:smoothScrollbar="false"     android:focusable="true" android:dividerHeight="0dip"     android:cacheColorHint="#00000000" android:divider="@drawable/divider" />   <!-- 引用聊天內容.xml -->   <LinearLayout android:layout_width="fill_parent"     android:layout_height="50.0dip" android:orientation="horizontal"     android:background="#ccc" android:paddingLeft="3dip"     android:paddingTop="3dip">     <Button android:id="@+id/chat_prev_page"       android:layout_width="wrap_content" android:layout_height="wrap_content"       android:background="@drawable/chat_prev_page" />     <TextView android:id="@+id/history_page" android:layout_width="30.0dip"       android:layout_height="25.0dip" android:gravity="center"       android:text="1/1"/>     <Button android:id="@+id/chat_next_page" android:layout_width="wrap_content"       android:layout_height="wrap_content" android:background="@drawable/chat_next_page" />     <Button android:id="@+id/delete_history" android:layout_width="wrap_content"       android:layout_height="wrap_content" android:background="@drawable/delete_history_button" />     <Button android:id="@+id/export_history" android:layout_width="wrap_content"       android:layout_height="wrap_content" android:background="@drawable/export_history_button" />     <Button android:id="@+id/back_chats_history"       android:layout_width="wrap_content" android:layout_height="wrap_content"        android:background="@drawable/back_btn"/>   </LinearLayout> </LinearLayout>

 message_layout.xml

<?xml version="1.0" encoding="UTF-8"?> <!-- 訊息內容的展示 --> <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:orientation="vertical"  >  <!-- android:background="@drawable/item_style" -->   <TextView android:id="@+id/message_view_sender_content"     android:layout_width="wrap_content" android:layout_height="wrap_content"     android:autoLink="all" />   <TextView android:id="@+id/message_view_timestamp"     android:layout_alignParentRight="true" android:layout_width="wrap_content"     android:layout_height="wrap_content" android:layout_below="@+id/message_view_message"     android:layout_gravity="right" /> </LinearLayout> 

最後來看看效果吧,別欺負我沒貼上資料庫建表語句,看下我的POJO類就知道我資料庫表怎麼建的

希望本文所述對大家的Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.