android實現(xiàn)listview分頁的方法
本文實例講述了android實現(xiàn)listview分頁的方法。分享給大家供大家參考。具體分析如下:
最近做了下listview的分頁,跟WEB上的分頁是一個意思,需要那幾個分頁參數(shù),不同的是sqlite中分頁的查詢語句,簡便的方法需要用Limit,Offset關(guān)鍵字,前者是查詢每頁展示的記錄數(shù),后者是越過多少記錄數(shù),說得明白點就是忽略前面多少行記錄之后,取多少行記錄
我分頁采用了一個重要的類Page,通過封裝Page類,做為參數(shù)傳遞進來,返回出去也是個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"; //-- 分頁參數(shù) --// protected int pageNo = 0;// 當前頁號<跟取數(shù)據(jù)的方式有關(guān)系> protected int pageSize = 1;// 每頁顯示的記錄數(shù) protected String orderBy = null; protected String order = null; protected boolean autoCount = true; //-- 返回結(jié)果 --// protected List<T> result = Collections.emptyList(); protected long totalCount = -1;// 總記錄數(shù) //-- 構(gòu)造函數(shù) --// public Page() { } public Page(final int pageSize) { setPageSize(pageSize); } public Page(final int pageSize, final boolean autoCount) { setPageSize(pageSize); setAutoCount(autoCount); } //-- 訪問查詢參數(shù)函數(shù) --// /** * 獲得當前頁的頁號,序號從0開始,默認為0. */ public int getPageNo() { return pageNo; } /** * 設置當前頁的頁號,序號從0開始,低于0時自動調(diào)整為0. */ public void setPageNo(final int pageNo) { this.pageNo = pageNo; if (pageNo < 0) { this.pageNo = 0; } } /** * 獲得每頁的記錄數(shù)量,默認為1. */ public int getPageSize() { return pageSize; } /** * 設置每頁的記錄數(shù)量,低于0時自動調(diào)整為0. */ public void setPageSize(final int pageSize) { this.pageSize = pageSize; if (pageSize < 0) { this.pageSize = 0; } } /** * 根據(jù)pageNo和pageSize計算當前頁第一條記錄在總結(jié)果集中的位置,序號從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; } /** * 查詢對象時是否自動另外執(zhí)行count查詢獲取總記錄數(shù), 默認為false. */ public boolean isAutoCount() { return autoCount; } /** * 查詢對象時是否自動另外執(zhí)行count查詢獲取總記錄數(shù). */ public void setAutoCount(final boolean autoCount) { this.autoCount = autoCount; } //-- 訪問查詢結(jié)果函數(shù) --// /** * 取得頁內(nèi)的記錄列表. */ public List<T> getResult() { return result; } /** * 設置頁內(nèi)的記錄列表. */ public void setResult(final List<T> result) { this.result = result; } /** * 取得總記錄數(shù), 默認值為-1. */ public long getTotalCount() { return totalCount; } /** * 設置總記錄數(shù). */ public void setTotalCount(final long totalCount) { this.totalCount = totalCount; } /** * 根據(jù)pageSize與totalCount計算總頁數(shù), 默認值為-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類里做的操作就是對總記錄數(shù)和結(jié)果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; } /** * 總記錄數(shù) */ 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; }
關(guān)于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; } } /** * 上一頁按鈕的監(jiān)聽事件 */ 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發(fā)送消息,更新UI } } }; /** * 下一頁按鈕的監(jiān)聽事件 */ 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發(fā)送消息,更新UI } } }; /** * 刪除歷史記錄按鈕監(jiān)聽器 */ OnClickListener deleteHistoryButtonListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }; /** 退出聊天界面監(jiān)聽器 */ 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" /> <!-- 引用聊天內(nèi)容.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"?> <!-- 消息內(nèi)容的展示 --> <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>
最后來看看效果吧,別欺負我沒貼上數(shù)據(jù)庫建表語句,看下我的POJO類就知道我數(shù)據(jù)庫表怎么建的
希望本文所述對大家的Android程序設計有所幫助。
- Android中實現(xiàn)多行、水平滾動的分頁的Gridview實例源碼
- Android中RecyclerView實現(xiàn)分頁滾動的方法詳解
- Android之ListView分頁加載數(shù)據(jù)功能實現(xiàn)代碼
- Android實現(xiàn)ListView分頁自動加載數(shù)據(jù)的方法
- Android Recyclerview實現(xiàn)水平分頁GridView效果示例
- Android實現(xiàn)簡單的分頁效果
- Android提高之SQLite分頁表格實現(xiàn)方法
- Android開發(fā)中滑動分頁功能實例詳解
- Android端代碼量非常小的分頁加載庫
相關(guān)文章
Android中使用DialogFragment編寫對話框的實例教程
這篇文章主要介紹了Android中使用DialogFragment編寫對話框的實例教程,DialogFragment也是一種Fragment,因而管理生命周期時比較給力,需要的朋友可以參考下2016-04-04Android Intent 用法全面總結(jié)及實例代碼
這篇文章主要介紹了Android Intent 用法全面總結(jié)的相關(guān)資料,并附實例代碼,需要的朋友可以參考下2016-09-09android內(nèi)存優(yōu)化之圖片優(yōu)化
對圖片本身進行操作。盡量不要使用setImageBitmap、setImageResource、BitmapFactory.decodeResource來設置一張大圖,因為這些方法在完成decode后,最終都是通過java層的createBitmap來完成的,需要消耗更多內(nèi)存2012-12-12Android 使用Vitamio打造自己的萬能播放器(4)——本地播放(快捷搜索、數(shù)據(jù)存儲)
本文主要介紹android Vitamio 本地播放功能(快捷搜索,數(shù)據(jù)存儲),這里提供實例代碼和效果圖,有需要的小伙伴可以參考下2016-07-07