編輯:Android 開發實例
前一篇談了 SQLite 的分頁讀取,但那個版本只是把資料印在文字方塊裡。這次往前一步:把「分頁 + 表格呈現」封裝成一個可重複使用的自訂控件。
執行結果:

這個控件分成「表格區」與「分頁列」兩塊,兩者都基於 GridView 實作。
網上多數 Android 表格範例用的是 ListView,兩者的取捨值得釐清:
由於資料表的欄位數由 Cursor 決定、事先無法預知,自適應能力才是刚需,所以這裡選 GridView。結構多變的資料表,用 GridView 是對的。
本控件的三個特點:自適應資料表結構(格大小統一)、支援分頁、表格區與分頁列各有事件回呼。
表格區與分頁列共用同一個格樣式:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#555555"
android:layout_height="wrap_content">
<TextView android:layout_below="@+id/ItemImage"
android:text="TextView01"
android:id="@+id/ItemText"
android:bufferType="normal"
android:singleLine="true"
android:background="#000000"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_margin="1dip"
android:layout_gravity="center"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/MainLinearLayout">
<Button android:layout_height="wrap_content" android:layout_width="fill_parent"
android:id="@+id/btnCreateDB" android:text="創建數據庫"></Button>
<Button android:layout_height="wrap_content" android:layout_width="fill_parent"
android:text="插入一串實驗數據" android:id="@+id/btnInsertRec"></Button>
<Button android:layout_height="wrap_content" android:id="@+id/btnClose"
android:text="關閉數據庫" android:layout_width="fill_parent"></Button>
</LinearLayout>
package com.testSQLite;
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class testSQLite extends Activity {
GVTable table;
Button btnCreateDB, btnInsert, btnClose;
SQLiteDatabase db;
int id;
private static final String TABLE_NAME = "stu";
private static final String ID = "id";
private static final String NAME = "name";
private static final String PHONE = "phone";
private static final String ADDRESS = "address";
private static final String AGE = "age";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCreateDB = (Button) this.findViewById(R.id.btnCreateDB);
btnCreateDB.setOnClickListener(new ClickEvent());
btnInsert = (Button) this.findViewById(R.id.btnInsertRec);
btnInsert.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btnClose);
btnClose.setOnClickListener(new ClickEvent());
table = new GVTable(this);
table.gvSetTableRowCount(8); // 每頁 8 列
table.setTableOnClickListener(new GVTable.OnTableClickListener() {
@Override
public void onTableClickListener(int x, int y, Cursor c) {
c.moveToPosition(y);
String str = c.getString(x) + " 位置:(" + String.valueOf(x)
+ "," + String.valueOf(y) + ")";
Toast.makeText(testSQLite.this, str, 1000).show();
}
});
table.setOnPageSwitchListener(new GVTable.OnPageSwitchListener() {
@Override
public void onPageSwitchListener(int pageID, int pageCount) {
String str = "共有" + String.valueOf(pageCount)
+ " 當前第" + String.valueOf(pageID) + "頁";
Toast.makeText(testSQLite.this, str, 1000).show();
}
});
LinearLayout ly = (LinearLayout) findViewById(R.id.MainLinearLayout);
ly.addView(table);
}
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v == btnCreateDB) {
CreateDB();
} else if (v == btnInsert) {
InsertRecord(16);
table.gvUpdatePageBar("select count(*) from " + TABLE_NAME, db);
table.gvReadyTable("select * from " + TABLE_NAME, db);
} else if (v == btnClose) {
table.gvRemoveAll();
db.close();
}
}
}
/** 在記憶體建立資料庫與資料表 */
void CreateDB() {
db = SQLiteDatabase.create(null);
Log.e("DB Path", db.getPath());
String sql = "CREATE TABLE " + TABLE_NAME + " ("
+ ID + " text not null, "
+ NAME + " text not null,"
+ ADDRESS + " text not null, "
+ PHONE + " text not null,"
+ AGE + " text not null );";
try {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL(sql);
} catch (SQLException e) { }
}
/** 插入 n 筆資料 */
void InsertRecord(int n) {
int total = id + n;
for (; id < total; id++) {
String sql = "insert into " + TABLE_NAME + " ("
+ ID + ", " + NAME + ", " + ADDRESS + ", " + PHONE + ", " + AGE
+ ") values('" + String.valueOf(id)
+ "', 'man','address','123456789','18');";
try {
db.execSQL(sql);
} catch (SQLException e) { }
}
}
}
package com.testSQLite;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class GVTable extends LinearLayout {
protected GridView gvTable, gvPage;
protected SimpleAdapter saPageID, saTable;
protected ArrayList<HashMap<String, String>> srcPageID, srcTable;
protected int TableRowCount = 10; // 每頁列數
protected int TableColCount = 0; // 每頁欄數
protected SQLiteDatabase db;
protected String rawSQL = "";
protected Cursor curTable;
protected OnTableClickListener clickListener; // 表格被點擊的回呼
protected OnPageSwitchListener switchListener; // 分頁切換的回呼
public GVTable(Context context) {
super(context);
this.setOrientation(VERTICAL);
// ---------- 表格區 ----------
gvTable = new GridView(context);
addView(gvTable, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
srcTable = new ArrayList<HashMap<String, String>>();
saTable = new SimpleAdapter(context, srcTable,
R.layout.items,
new String[] { "ItemText" },
new int[] { R.id.ItemText });
gvTable.setAdapter(saTable);
gvTable.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// 第 0 列是標題列,要扣掉
int y = arg2 / curTable.getColumnCount() - 1;
int x = arg2 % curTable.getColumnCount();
if (clickListener != null && y != -1) {
clickListener.onTableClickListener(x, y, curTable);
}
}
});
// ---------- 分頁列 ----------
gvPage = new GridView(context);
gvPage.setColumnWidth(40);
gvPage.setNumColumns(GridView.AUTO_FIT);
addView(gvPage, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
srcPageID = new ArrayList<HashMap<String, String>>();
saPageID = new SimpleAdapter(context, srcPageID,
R.layout.items,
new String[] { "ItemText" },
new int[] { R.id.ItemText });
gvPage.setAdapter(saPageID);
gvPage.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
LoadTable(arg2);
if (switchListener != null) {
switchListener.onPageSwitchListener(arg2, srcPageID.size());
}
}
});
}
/** 清除所有資料 */
public void gvRemoveAll() {
if (this.curTable != null) curTable.close();
srcTable.clear();
saTable.notifyDataSetChanged();
srcPageID.clear();
saPageID.notifyDataSetChanged();
}
/**
* 讀取指定分頁的資料
* Limit 9 Offset 10 表示跳過 10 筆取 9 筆
* @param pageID 分頁序號
*/
protected void LoadTable(int pageID) {
if (curTable != null) curTable.close(); // 釋放上次的資料
String sql = rawSQL + " Limit " + String.valueOf(TableRowCount)
+ " Offset " + String.valueOf(pageID * TableRowCount);
curTable = db.rawQuery(sql, null);
// 這一行是「表現為表格」的關鍵
gvTable.setNumColumns(curTable.getColumnCount());
TableColCount = curTable.getColumnCount();
srcTable.clear();
// 先放標題列
int colCount = curTable.getColumnCount();
for (int i = 0; i < colCount; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("ItemText", curTable.getColumnName(i));
srcTable.add(map);
}
// 再放資料列
int recCount = curTable.getCount();
for (int i = 0; i < recCount; i++) {
curTable.moveToPosition(i);
for (int ii = 0; ii < colCount; ii++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("ItemText", curTable.getString(ii));
srcTable.add(map);
}
}
saTable.notifyDataSetChanged();
}
/** 設定每頁最多顯示的列數 */
public void gvSetTableRowCount(int row) {
TableRowCount = row;
}
public int gvGetTableRowCount() {
return TableRowCount;
}
/** 取得目前分頁的 Cursor */
public Cursor gvGetCurrentTable() {
return curTable;
}
/**
* 準備分頁顯示資料
* @param rawSQL SQL 語句
* @param db 資料庫
*/
public void gvReadyTable(String rawSQL, SQLiteDatabase db) {
this.rawSQL = rawSQL;
this.db = db;
}
/**
* 刷新分頁列,更新按鈕數量
* @param sql SQL 語句
* @param db 資料庫
*/
public void gvUpdatePageBar(String sql, SQLiteDatabase db) {
Cursor rec = db.rawQuery(sql, null);
rec.moveToLast();
long recSize = rec.getLong(0);
rec.close();
int pageNum = (int) (recSize / TableRowCount) + 1;
srcPageID.clear();
for (int i = 0; i < pageNum; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("ItemText", "No." + String.valueOf(i));
srcPageID.add(map);
}
saPageID.notifyDataSetChanged();
}
/** 表格被點擊時的回呼 */
public void setTableOnClickListener(OnTableClickListener click) {
this.clickListener = click;
}
public interface OnTableClickListener {
public void onTableClickListener(int x, int y, Cursor c);
}
/** 分頁列被點擊時的回呼 */
public void setOnPageSwitchListener(OnPageSwitchListener pageSwitch) {
this.switchListener = pageSwitch;
}
public interface OnPageSwitchListener {
public void onPageSwitchListener(int pageID, int pageCount);
}
}
setNumColumns 是「變成表格」的關鍵。GridView 本質上是網格,預設會自動換行排列。加上這行、把欄數設為 Cursor 的欄位數,它才會變成一行一列的表格。這也是「自適應」的實現點——欄數完全由資料決定。
用「第 0 列放欄名」的技巧做標題列。LoadTable 裡先把 getColumnName() 逐一塞進 srcTable,再放資料列。這樣標題與內容用同一個 Adapter、同一套樣式,不必另外做表頭 View。點擊時 y = arg2 / 欄數 - 1 扣掉標題列,並用 y != -1 過濾掉點在表頭上的情況。
回呼介面而非直接操作。GVTable 對外只暴露 OnTableClickListener 與 OnPageSwitchListener 兩個介面,把 Cursor 與座標當參數傳出去,讓使用者自行決定要怎麼用。這是複合控件封裝的正確做法——控件不該假設使用者的業務邏輯。
gvReadyTable 與 gvUpdatePageBar 的分工。前者存 SQL 與 db 參照但不查詢,後者才實際刷新分頁列。分成兩步是因為建立資料與渲染分頁鈕往往不是同一時機發生。
誠實指出幾處在正式專案會遇到的問題。
Cursor 生命週期不安全。gvGetCurrentTable() 把 Cursor 直接交給外部,而 LoadTable 下次被呼叫時又會 close 掉它。若外部持有參照並在使用中換頁,就會拿到已關閉的 Cursor 而崩潰。較好的做法是傳資料副本(List<List<String>>)而非 Cursor。
SimpleAdapter 不適合大量資料。它每次 notifyDataSetChanged 都會為每個格建立 View 對照,且完全沒有 View 複用。每頁 8 列 5 欄是 40 個格,還算可以;若列數上百就會明顯卡頓。
分頁列會無限延伸。資料一多,頁數可能幾十頁,GridView 的 AUTO_FIT 會把它排成好幾列,佔掉半個螢幕。實務上應該限制顯示的頁碼(例如當前頁前後各三頁 + 首尾)。
SQL 字串拼接與主鍵型別的問題同前一篇所述,這裡不重複。
最後談替代方案。這個控件示範的「自適應表格 + 分頁」在今日有更省事的做法:Room + Paging 3 + RecyclerView。Room 負責資料存取並編譯期驗證 SQL,Paging 3 自動處理載入更多與資料變動,RecyclerView 則提供 ViewHolder 複用與差異更新。原本 GVTable 裡手刻的「算頁數、切 Offset、刷新分頁列」全部由函式庫代管。
若只是要在螢幕上顯示一堆表格資料,TableLayout 搭配 ScrollView 反而最直接——它就是為靜態表格而生,不需要 Adapter 這層間接。GVTable 這套封裝真正適用的場景是「欄位動態、資料量大、需要互動」的組合,評估需求後再決定是否值得自己造輪子。
自訂控制項打造 Android 滑動解鎖九宮格完整實作
本文概述:滑動解鎖九宮格的分析:1、需要自訂控制項; 2、需要改寫事件 onTouchEvent(); 3、需要為九個點設定序號與座標,這裡用 Map 類即可; 4、需要
Android 載入動畫實作:用 Loading Spinner 讓使用者知道「系統還在忙」
當 App 在背後跑一段耗時的工作(下載、查詢、運算)時,畫面如果完全沒有反應,使用者往往會以為程式當掉了,甚至直接把它關掉。這時候一個小小的進度提示,就能大幅改善操作體
Android 開發實作:日曆專案(三)建立樣式與資源
接續日曆專案的進度,這一階段要把視覺資源整理乾淨:顏色、尺寸、Color State List、drawable 與 style 全部抽成獨立檔案。日曆的表格線以 Cel
Android 網絡通信案例:HttpURLConnection、HttpClient 與 Socket 三種路線比較
因為專案需要,我把 Android 的網絡通信方式整理了一遍,整體思路與 Java 平台相當接近。 Android 平台提供了多組 API 供開發者選用: 無論走哪一