編輯:關於 Android 程式設計
在 Android 開發中,把 SQLite 數據庫裡的記錄以「表格」的形式呈現給用戶,是一個非常典型的需求。本文將帶你一步步實現這樣的效果:先搭建帶有表頭的整體布局,再定義每一列的樣式,最後通過自定義的適配器(Adapter)把游標數據填充進列表,並附上增刪改的交互操作。
要讓界面看起來像一張表格,我們需要兩層布局協作:頂部是一行「表頭」,用水平的線性布局把三個 TextView 並排擺放,分別顯示「編號、姓名、年齡」三列的標題;下方則放一個 ListView,用來逐行展示每一條記錄。而每一行的具體樣式,則由我們自己編寫的適配器來控制。
這裡有個小技巧:在相鄰兩列之間插入一個寬度為 0.5px 的 View,並給它設置灰色背景,就能實現「豎線分隔」的視覺效果。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/id"
android:layout_width="0dip"
android:layout_height="35dip"
android:layout_weight="2"
android:textColor="#CD3700"
android:textSize="20sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#000000"
android:textSize="17sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/age"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000000"
android:textSize="17sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
</LinearLayout>
整個布局的核心,就是利用 View 充當「分隔線」,把三個 TextView 排布在同一條水平線上。實際使用時,你只需要把這段表頭布局與 ListView 一起放進一個垂直的 LinearLayout 中即可。
ListView 中每一「項」的樣式,需要單獨定義。它的結構與表頭幾乎一致——用 View 分隔每一列,用 TextView 顯示具體數據,全部放在一個水平的線性布局裡。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/id"
android:layout_width="0dip"
android:layout_height="35dip"
android:layout_weight="2"
android:textColor="#CD3700"
android:textSize="20sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#000000"
android:textSize="17sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
<TextView
android:id="@+id/age"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000000"
android:textSize="17sp" />
<View
android:layout_width="0.5px"
android:layout_height="fill_parent"
android:background="#B8B8B8"
android:visibility="visible" />
</LinearLayout>
主體布局完成後,接下來就是關鍵的一步:寫一個適配器,把游標(Cursor)中的每一行記錄映射到列表項上。Android 提供了一個方便的 SimpleCursorAdapter,它能夠自動把 Cursor 的列數據綁定到指定的 TextView 或 ImageView 上。我們可以繼承它,並重寫 getView 方法來實現一些個性化效果,例如「隔行換色」。
package com.example.gird;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView != null) {
view = convertView;
} else {
view = super.getView(position, convertView, parent);
}
/* author:conowen
* date:2012.4.2
* MySimpleCursorAdapter */
int[] colors = { Color.WHITE, Color.rgb(219, 238, 244) };// RGB 顏色
view.setBackgroundColor(colors[position % 2]);// 每隔 item 之間顏色不同
return super.getView(position, view, parent);
}
}
這段代碼的重點在於重寫 getView 方法,三個參數各有含義:
我們利用 position % 2 對兩種顏色取餘,就實現了相鄰行背景色交替的效果,讓表格更易閱讀。
最後,在主 Activity 中完成數據庫的創建、數據插入、列表展示以及長按交互。這裡我們先刪除舊表再重建,插入 20 條測試數據,然後加載列表;同時為 ListView 註冊長按監聽,彈出「更新 / 刪除 / 取消」的操作菜單。
package com.example.gird;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class GridActivity extends Activity {
public int DB_VERSION = 1;
SQLiteDatabase db;
// DbHelper 類在 DbHelper.java 文件中創建
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 建立並打開數據庫
db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
db.execSQL("DROP TABLE IF EXISTS person");
// 創建 person 表
db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
// 插入數據
for (int i = 0; i < 20; i++) {
Person person = new Person();
person.name = "john" + i;
person.age = 30 - i;
db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[] {
person.name, person.age });
}
lv = (ListView) findViewById(R.id.lv);
updatelistview();
// 添加一個長按事件
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
// 實例化一個彈出框
new AlertDialog.Builder(GridActivity.this)
.setTitle("選擇操作")
.setItems(new String[] { "更新", "刪除", "取消" },
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 更新內容
case 0:
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(
R.layout.dialog,
(ViewGroup) findViewById(R.id.dialog));
EditText nameTxt = (EditText) layout
.findViewById(R.id.editText1);
TextView ageTxt = (EditText) layout
.findViewById(R.id.editText2);
SQLiteCursor s_old = (SQLiteCursor) lv
.getItemAtPosition(position);
final int _id_old = s_old.getInt(s_old
.getColumnIndex("_id"));
final String name_old = s_old.getString(s_old
.getColumnIndex("name"));
final String age_old = s_old.getString(s_old
.getColumnIndex("age"));
nameTxt.setText(name_old);
ageTxt.setText(age_old);
new AlertDialog.Builder(GridActivity.this)
.setTitle("更新")
.setView(layout)
.setPositiveButton("確定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ContentValues cv = new ContentValues();
String temp_name = ((EditText) layout
.findViewById(R.id.editText1))
.getText().toString();
String temp_age = ((EditText) layout
.findViewById(R.id.editText2))
.getText().toString();
cv.put("_id", _id_old);
cv.put("name", temp_name);
cv.put("age", temp_age);
String[] id_index = { String.valueOf(_id_old) };
db.update("person", cv, "_id=?", id_index);
updatelistview();
}
})
.setNegativeButton("取消", null).show();
break;
// 刪除記錄
case 1:
SQLiteCursor s = (SQLiteCursor) lv
.getItemAtPosition(position);
final int _id = s.getInt(s.getColumnIndex("_id"));
String name = s.getString(s.getColumnIndex("name"));
Log.i("id ::", _id + "");
new AlertDialog.Builder(GridActivity.this)
.setTitle("確定刪除" + name + "嗎?")
.setPositiveButton("確定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
db.execSQL("delete from person where _id =?",
new Integer[] { _id });
updatelistview();
}
})
.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
break;
// 取消操作
case 2:
break;
}
}
}).show();
return false;
}
});
}
// 更新 listview
public void updatelistview() {
Cursor cr = db.query("person", null, null, null, null, null, null);
String id = cr.getColumnName(0);
String name = cr.getColumnName(1);
String age = cr.getColumnName(2);
String[] ColumnNames = { id, name, age };
ListAdapter adapter = new MySimpleCursorAdapter(this,
R.layout.listviewlayout, cr, ColumnNames, new int[] {
R.id.id, R.id.name, R.id.age });
lv.setAdapter(adapter);
}
@Override
protected void onPause() {
onDestroy();
Log.i("message", "數據庫連接銷毀");
super.onPause();
}
@Override
protected void onDestroy() {// 關閉數據庫
super.onDestroy();
if (db != null) {
db.close();
}
}
}
在 updatelistview() 方法中,我們先查詢出 person 表的全部數據得到 Cursor,再取出三個列名,最後用自定義的 MySimpleCursorAdapter 把數據與布局中的三個 TextView 一一對應起來。每執行一次更新或刪除,都重新調用該方法刷新列表,界面便能即時反映數據庫的最新狀態。別忘了在 onDestroy() 中關閉數據庫連接,避免資源洩漏。
Android TabWidget 標籤切換頁的實作應用
TabWidget 能實現類似 Android 聯絡人那樣的多標籤切換效果,讓使用者透過點擊不同標籤顯示不同內容。要實現它,首先要認識 TabHost——一個用來容納多個
Android 事件分發機制實測:從 Logcat 逐行拆解 dispatchTouchEvent
事件分發機制是 Android 面試與實務中的必考題,但只看結論很容易記錯。最可靠的方式,是自己寫幾個自訂 ViewGroup,在每個方法裡打 Log,然後拿真實的輸出對
Android 程式呼叫系統分享功能的實作範例
本文將說明如何在 Android 程式中呼叫系統的分享功能,涵蓋分享文字、單張圖片與多張圖片三種情境,分享給大家參考。 /** * 調用系統的分享功能 * Crea
Android 繪圖(二):Canvas 畫布常用 API 詳解與實戰
今天這篇,我們來好好聊聊 Canvas。Canvas 是畫布,用來響應繪畫(Draw)的調用,並把結果寫入 Bitmap。先看看官方文檔對 Canvas 的描述: The