編輯:Android 開發實例
上一篇我們用 EditText 把 SQLite 的查詢結果一頁一頁打印出來,那只能算是驗證思路的雛形。這一篇往前多走一步:把「分頁」與「表格呈現」兩件事一起封裝成一個獨立控件 GVTable,之後只要傳一句 SQL 進去,就能得到一個帶頁碼切換的表格。
網上大部分「Android 做表格」的範例都建立在 ListView 之上。兩者放在一起比,性格其實很清楚:
所以判斷標準很簡單:資料表結構固定、每列樣式需要變化,走 ListView;資料表結構由 SQL 決定、欄數不寫死,走 GridView。本文的控件走的是第二條路。
GVTable 繼承自 LinearLayout,內部縱向堆疊兩個 GridView:
Cursor.getColumnCount() 決定。對外則暴露兩組回呼:OnTableClickListener 回傳被點中的座標 (x, y) 與當前頁的 Cursor;OnPageSwitchListener 回傳頁碼與總頁數。這樣使用端不必知道內部怎麼排格子,拿著 Cursor 就能自己決定要顯示什麼。
分頁的核心就一句 SQL:select * from stu Limit 8 Offset 16,意思是从 stu 表跳過 16 列、取 8 列。每次換頁都把 Offset = pageID * TableRowCount 重新拼一次,舊的 Cursor 記得先 close() 釋放。
整個控件最關鍵的一行是 gvTable.setNumColumns(curTable.getColumnCount())。GridView 預設是自動排列,欄數一旦等於結果集的欄數,資料就會被切成一列一列,視覺上自然成了表格。
GridView 的 onItemClick 只給你一維的 position。因為第 0 列被標題佔用,所以:
int y = position / curTable.getColumnCount() - 1; // 列號,扣掉標題列
int x = position % curTable.getColumnCount(); // 欄號
if (clickListener != null && y != -1) { // y == -1 表示點在標題列上
clickListener.onTableClickListener(x, y, curTable);
}
表格區與分頁欄共用同一個格子版面,一個 TextView 就夠了,靠 layout_margin="1dip" 留出的細縫當作表格線。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#555555">
<TextView
android:id="@+id/ItemText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="1dip"
android:background="#000000"
android:gravity="center"
android:singleLine="true"
android:text="TextView01" />
</LinearLayout>
主畫面只放三個按鈕:建庫、插入測試資料、關庫。控件本身在程式碼裡 new 出來再 addView 進去,方便說明它是完全獨立的。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/MainLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnCreateDB"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="創建數據庫" />
<Button
android:id="@+id/btnInsertRec"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="插入一串實驗數據" />
<Button
android:id="@+id/btnClose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="關閉數據庫" />
</LinearLayout>
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.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
public class GVTable extends LinearLayout {
protected GridView gvTable, gvPage;
protected SimpleAdapter saPageID, saTable; // 適配器
protected ArrayList<HashMap<String, String>> srcPageID, srcTable; // 資料源
protected int TableRowCount = 10; // 每頁的 Row 總數
protected int TableColCount = 0; // 每頁的 Column 數量
protected SQLiteDatabase db;
protected String rawSQL = "";
protected Cursor curTable; // 分頁時使用的 Cursor
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) {
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();
}
/**
* 讀取指定頁的資料
* SQL: Select * From TABLE_NAME Limit 9 Offset 10;
* 表示跳過 10 列、取 9 列
*/
protected void LoadTable(int pageID) {
if (curTable != null) { // 釋放上一次的資料
curTable.close();
}
String sql = rawSQL + " Limit " + TableRowCount
+ " Offset " + 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;
}
/** 準備分頁顯示:傳入 SQL 與已開啟的資料庫 */
public void gvReadyTable(String rawSQL, SQLiteDatabase db) {
this.rawSQL = rawSQL;
this.db = 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);
}
}
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 列
LinearLayout ly = (LinearLayout) findViewById(R.id.MainLinearLayout);
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();
}
});
ly.addView(table);
}
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v == btnCreateDB) {
CreateDB();
} else if (v == btnInsert) {
InsertRecord(16); // 插入 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());
Log.e("DB amount", String.valueOf(databaseList().length));
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) {
}
}
}
}
gvSetTableRowCount() 決定每頁幾列,這一步會直接影響頁數計算。gvUpdatePageBar() 先用 select count(*) 撈總筆數,算出頁數並產生頁碼。gvReadyTable() 只是把 SQL 與資料庫物件存起來,還不查詢。LoadTable() 拼出 Limit/Offset、重查、重填 adapter。把「查詢 statement」與「查詢時機」拆開,是這個控件可以重複使用的原因;同一個 GVTable 拿去餵不同的 SQL,不需要改一行內部代碼。
頁數目前用 (int)(recSize / TableRowCount) + 1 計算,筆數剛好整除時會多出一頁空白頁,實務上改成向上取整(Math.ceil)會乾淨一些。另外每頁都是重新 rawQuery,資料量很大時可以考慮改用 SQLiteCursor 搭配 CursorAdapter,讓 ListView/GridView 自己管理視窗,不必把整頁資料攤平成二維列表。
AudioManager 實戰:用程式控制鈴聲模式與音量
想要讓 App 直接切換手機的鈴聲模式(正常、靜音、震動),Android 提供了 AudioManager 這個系統服務。本文示範如何取得它、切換模式、讀回目前狀態,並
Android 簡易音樂播放器實作:從介面到背景播放
這篇文章整理一個適合入門的 Android 音樂播放器範例,重點在於把播放控制交給背景 Service,再透過 Binder 讓 Activity 與 Service
Android 應用本地化:讓同一個 App 說不同語言
一支 Android App 可能被安裝在世界各地、面對使用不同語言的使用者。如果介面文字全部寫死在程式碼裡,就無法適配這些環境。所謂本地化(Localization),
Android 仿微信朋友圈九宮格圖片查看器實現
打開微信朋友圈,你會發現一個經典的「九宮格」圖片區域,點擊任意一張圖就能進入大圖查看頁,還支援滑動切換與縮放。這樣的交互幾乎是所有社交類應用的標配。本文就帶你從零實現一個