Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 ListView 實作自適應表格:每格寬度都能不同

編輯:Android 開發實例

先前有文章談過用 GridView 做表格,這次換 ListView。兩者的取捨值得先講清楚:

  • GridView:每格尺寸固定,但自適應表格結構容易,也能定位到「某一格」。
  • ListView:每一格(每一列)的內部可以完全自訂,寬度、內容、控件種類都行,但只能定位到「某一列」,無法定位到列內的某一格。

所以選擇標準很單純:需要打到格精度就用 GridView;需要每列樣式各異、內容長度不一,就用 ListView。

先看執行結果:

本文實作的 ListView 表格有兩個特點:不需要預先定義 XML 樣式(這正是自適應的核心),並且由於 ListView 被放進 HorizontalScrollView,遇到欄位多或欄位內容很長的資料表,也能靠橫向捲動應付。

版面檔 main.xml

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

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自適應實現表格");

        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);

        for (int i = 0; i < 12; i++) {
            table.add(new TableRow(cells));
        }

        lv.setAdapter(new TableAdapter(this, table));
        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(列的可視元件)→ ListView。逐層往上組裝,職責分明。

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);
    }

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

    /** 表格列的可視元件 */
    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);  // 預留 1px 空隙製造邊框

                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);  // 透出空隙成為表格線
        }
    }

    /** 表格列 */
    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];
        }
    }

    /** 表格格單元 */
    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;
        }
    }
}

幾個值得學的設計手法

用背景色製造表格線。每個 cell 設 setMargins(0, 0, 1, 1) 預留一像素間距,cell 本身塗黑、外層 Layout 塗白,白底從縫隙透出來就成了格線。這個技巧不需要任何 drawable 資源,乾淨俐落。

width 存在資料裡而非寫死在 XML。因為每格寬度可能不同,所以把 width 當成 TableCell 的屬性,由建立資料時決定。這正是「自適應」的實現方式。

getView 沒有複用 convertView。這在效能上是不理想的寫法。正式專案應該在 convertView 為 null 時才建立新 View,否則每次捲動都配置大量物件,容易卡頓。範例為求程式碼清楚而省略了這段最佳化,實作時請補上。

最後,若你今天要做類似需求,RecyclerView 才是正解。它的 LayoutManager 機制天生支援橫向捲動,回收複用效率遠高於 ListView,而且沒有 ListView 那種「只能定位到列」的限制。本文的三層結構封裝思路(Cell / Row / Adapter)在遷移時可以原封不動沿用。

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