Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android實現listview分頁的方法

android實現listview分頁的方法

編輯:關於Android編程

本文實例講述了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程序設計有所幫助。

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