Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據庫實戰:用 ListView 打造表格化數據展示

編輯:關於 Android 程式設計

在 Android 開發中,把 SQLite 數據庫裡的記錄以「表格」的形式呈現給用戶,是一個非常典型的需求。本文將帶你一步步實現這樣的效果:先搭建帶有表頭的整體布局,再定義每一列的樣式,最後通過自定義的適配器(Adapter)把游標數據填充進列表,並附上增刪改的交互操作。

一、整體思路

要讓界面看起來像一張表格,我們需要兩層布局協作:頂部是一行「表頭」,用水平的線性布局把三個 TextView 並排擺放,分別顯示「編號、姓名、年齡」三列的標題;下方則放一個 ListView,用來逐行展示每一條記錄。而每一行的具體樣式,則由我們自己編寫的適配器來控制。

這裡有個小技巧:在相鄰兩列之間插入一個寬度為 0.5px 的 View,並給它設置灰色背景,就能實現「豎線分隔」的視覺效果。

二、主布局文件 main.xml

<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 中即可。

三、單行布局文件 itemlayout.xml

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:當前項在列表中的位置。
  • convertView:即將顯示的組件項。這裡體現了 Android 的「視圖複用」機制——系統不會每次都重新 new 一個 View,而是優先從緩存中查找可重用的對象,找不到時才創建新對象,這樣能顯著提升列表的滑動性能。
  • parent:指明這些項最終依附的父容器,也就是 ListView。

我們利用 position % 2 對兩種顏色取餘,就實現了相鄰行背景色交替的效果,讓表格更易閱讀。

五、主 Activity 邏輯

最後,在主 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() 中關閉數據庫連接,避免資源洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved