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

Android 效能優化(十五):用 ListView 自適應實作表格

編輯:Android 開發實例

     上次介紹了用 GridView 實作表格,這次換 ListView 上場,看它怎麼撐起一個自適應的表格。

先講兩者的取捨。GridView 做自適應表格相對輕鬆,但代價是每一格的大小固定;ListView 走的路線不同——它允許每一格擁有不同尺寸,靈活度更高,相對地自適應的實作也複雜一些。另外還有一個差異:GridView 能精準定位到某個格單元,ListView 的點擊事件卻只到「列」為止。所以結論還是那句老話:依實際使用情境決定要用 GridView 還是 ListView。

先看程式執行的效果:

本文實作的 ListView 表格,每一格尺寸可以不一致,內容可以是文字(TextView)也可以是圖片(ImageView),而且不需要預先定義 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;

/**
 * @author hellogv
 */
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>();

        // 定義標題列,每行 5 個單元
        TableCell[] titles = new TableCell[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));

        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 是整個自適應表格的核心:

PS:TableCell 是格單元的類別,TableRow 是表格列的類別,TableRowView 則是負責把列畫出來的元件。實作的組合順序為: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);
    }

    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);
                }
            }
            // 列的背景設為白色,透過格之間的 1px 空隙呈現表格線
            this.setBackgroundColor(Color.WHITE);
        }
    }

    /**
     * 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;
        }
    }
}

整份設計的巧思其實集中在一個小細節:格與格之間刻意留了 1px 的 margin,再把列的背景設成白色、格子設成黑色,表格線就憑空生出來了——不需要真的畫邊框。

不過 getView 這裡每次都 new 一個 TableRowView 回來,實務上是效能隱憂。ListView 之所以提供 convertView 參數,就是為了讓你重複使用回收的 View;正式專案裡應該加上 ViewHolder 或攔截 convertView 的複用邏輯,否則捲動大量資料時很容易卡頓。

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