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

ListView 自適應表格實作:讓每個單元格都能自訂尺寸

編輯:關於 Android 開發

用 ListView 拼出一張會自適應的表格,是不少 Android 新手會卡住的地方。老實說,如果只講「自適應表格」,GridView 其實更好寫;但 GridView 有個硬性限制——每個格子的寬高必須一致。反過來說,ListView 允許每一格大小不同,彈性大得多,代價是實作上也得自己多處理一些細節。

兩者還有一個關鍵差異:GridView 的點擊可以精準定位到「某一格」,而 ListView 的 OnItemClick 只能定位到「某一列」。所以選擇哪一個,取決於你的表格是規則矩陣,還是不規則排版。本文示範的 ListView 版本具備幾個特性:

  • 每個單元格寬高可各自指定,不必統一;
  • 單元格內容可以是文字(TextView),也可以是圖片(ImageView);
  • 完全用程式碼動態組出樣式,不需要預先寫死 XML 版面(這正是「自適應」的核心精神);
  • ListView 外層包一個 HorizontalScrollView,因此欄位多、文字長的表格也能靠水平滑動完整呈現。

一、版面配置 main.xml

結構非常精簡:一個直向 LinearLayout 裡放 HorizontalScrollView,ScrollView 裡再放 ListView。注意 ListView 的寬度設為 wrap_content,讓它能依內容撐開,而不是被螢幕寬度鎖死。

<?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">

    <HorizontalScrollView
        android:id="@+id/HorizontalScrollView01"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <ListView
            android:id="@+id/ListView01"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"></ListView>
    </HorizontalScrollView>
</LinearLayout>

二、主程式 testMyListView.java

這裡先以螢幕寬度除以欄數算出基準欄寬,再刻意讓每一列的欄寬逐一遞增 8px,用來驗證「每格大小可不同」這件事。最後一列刻意放一張圖片,示範混合內容的排版。

package com.testMyListView;

import java.util.ArrayList;

import com.testMyListView.TableAdapter.TableCell;
import com.testMyListView.TableAdapter.TableRow;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

public class testMyListView extends Activity {

    ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.setTitle("ListView 自適應實現表格 --- hellogv");

        lv = (ListView) this.findViewById(R.id.ListView01);

        ArrayList<TableRow> table = new ArrayList<TableRow>();

        TableCell[] titles = new TableCell[5];   // 每列 5 個單元
        int width = this.getWindowManager().getDefaultDisplay().getWidth() / titles.length;

        // 建立標題列
        for (int i = 0; i < titles.length; i++) {
            titles[i] = new TableCell("標題" + String.valueOf(i),
                    width + 8 * i, LayoutParams.FILL_PARENT, TableCell.STRING);
        }
        table.add(new TableRow(titles));

        // 建立資料列
        TableCell[] cells = new TableCell[5];
        for (int i = 0; i < cells.length - 1; i++) {
            cells[i] = new TableCell("No." + String.valueOf(i),
                    titles[i].width, LayoutParams.FILL_PARENT, TableCell.STRING);
        }
        cells[cells.length - 1] = new TableCell(R.drawable.icon,
                titles[cells.length - 1].width,
                LayoutParams.WRAP_CONTENT, TableCell.IMAGE);

        // 重複加入 12 列資料
        for (int i = 0; i < 12; i++) {
            table.add(new TableRow(cells));
        }

        TableAdapter tableAdapter = new TableAdapter(this, table);
        lv.setAdapter(tableAdapter);
        lv.setOnItemClickListener(new ItemClickEvent());
    }

    class ItemClickEvent implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
            Toast.makeText(testMyListView.this,
                    "選中第" + String.valueOf(arg2) + "列", 500).show();
        }
    }
}

三、表格核心 TableAdapter.java

整個設計可以拆成三層,組裝順序是:TableCell(單元格資料)→ TableRow(列資料)→ TableRowView(負責把一列畫出來的 View)→ ListView。

有兩個實作細節值得留意。第一,邊框並不是真的畫線,而是靠 LayoutParams 的右下 margin 各留 1px 空隙,再讓列的底色(白色)透出來,於是視覺上就出現了格線。第二,getView 每次都 new 一個新的 TableRowView,這在資料量小、欄寬不固定的場景下最簡單直觀;若要進一步優化大量資料的捲動效能,可以改成複用 convertView 並只在資料變動時更新內容。

package com.testMyListView;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TableAdapter extends BaseAdapter {

    private Context context;
    private List<TableRow> table;

    public TableAdapter(Context context, List<TableRow> table) {
        this.context = context;
        this.table = table;
    }

    @Override
    public int getCount() {
        return table.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public TableRow getItem(int position) {
        return table.get(position);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        TableRow tableRow = table.get(position);
        return new TableRowView(this.context, tableRow);
    }

    /**
     * TableRowView:負責把一整列的樣式畫出來
     */
    class TableRowView extends LinearLayout {

        public TableRowView(Context context, TableRow tableRow) {
            super(context);
            this.setOrientation(LinearLayout.HORIZONTAL);

            for (int i = 0; i < tableRow.getSize(); i++) {   // 逐格加入
                TableCell tableCell = tableRow.getCellValue(i);

                // 依單元格指定的大小建立版面參數
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        tableCell.width, tableCell.height);
                layoutParams.setMargins(0, 0, 1, 1);   // 留出空隙充當格線

                if (tableCell.type == TableCell.STRING) {
                    TextView textCell = new TextView(context);
                    textCell.setLines(1);
                    textCell.setGravity(Gravity.CENTER);
                    textCell.setBackgroundColor(Color.BLACK);
                    textCell.setText(String.valueOf(tableCell.value));
                    addView(textCell, layoutParams);
                } else if (tableCell.type == TableCell.IMAGE) {
                    ImageView imgCell = new ImageView(context);
                    imgCell.setBackgroundColor(Color.BLACK);
                    imgCell.setImageResource((Integer) tableCell.value);
                    addView(imgCell, layoutParams);
                }
            }

            this.setBackgroundColor(Color.WHITE);   // 白色底,讓 1px 空隙變成格線
        }
    }

    /**
     * TableRow:代表表格中的一列
     */
    static public class TableRow {
        private TableCell[] cell;

        public TableRow(TableCell[] cell) {
            this.cell = cell;
        }

        public int getSize() {
            return cell.length;
        }

        public TableCell getCellValue(int index) {
            if (index >= cell.length) {
                return null;
            }
            return cell[index];
        }
    }

    /**
     * TableCell:代表表格中的一個單元格
     */
    static public class TableCell {
        static public final int STRING = 0;
        static public final int IMAGE  = 1;

        public Object value;
        public int width;
        public int height;
        private int type;

        public TableCell(Object value, int width, int height, int type) {
            this.value = value;
            this.width = width;
            this.height = height;
            this.type = type;
        }
    }
}

選 ListView 還是 GridView?

如果你的表格是規則矩陣、需要點擊定位到單一格,GridView 更省事;如果欄寬需要不規則變化、內容要混排文字與圖片,那麼 ListView 這種「自己組 View」的做法反而更好掌控。兩者沒有絕對優劣,關鍵是先把需求想清楚,再決定要用哪個容器。

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