編輯:關於 Android 程式設計
先前介紹過用 GridView 做表格,這次改用 ListView。GridView 更容易做出自適應表格,但每個格子的尺寸固定;ListView 的做法可以讓每一格大小不一,代價是實作複雜度上升(畢竟格位尺寸不統一)。此外,GridView 的表格能定位到某個具體格位,ListView 則只能定位到「列」的層級。所以結論還是那句老話:依實際使用情境選擇 GridView 或 ListView。
先來看執行效果:

本文實作的 ListView 表格有兩個特點:每個格位尺寸可以不同,內容可以是文字(TextView)或圖片(ImageView);而且不需要預先定義 XML 樣式,這正是「自適應」的核心目標。另外因為 ListView 被放進 HorizontalScrollView 裡,對於欄位較多、或欄位內容較長的資料表,也能很好地撐開寬度。
<?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_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/ListView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>
</LinearLayout>
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]; // 每行 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();
}
}
}
這裡有個三層的結構值得記住: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);
}
}
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;
}
}
}
這裡有個巧妙的小技巧:格位之間以 setMargins(0, 0, 1, 1) 預留 1px 間距,每格背景設為黑色,而整列的容器背景設為白色。這樣一來,黑色會從間距中透出來,形成均勻的網格線——完全不需要畫任何 canvas,也不需要 NinePatch 圖。這是自適應表格能「不預先定義樣式」的關鍵之一。
實作上仍有兩處值得改良:一是 getView() 每次都 new 一個新的 TableRowView,完全沒有複用 convertView,列數多時會有明顯的效能與 GC 壓力,可以依 tableRow 是否相同來決定要不要複用;二是把 ListView 塞進 HorizontalScrollView 會破壞 ListView 自身的滾動回收機制(ListView 需要明確高度才能計算可視範圍),實務上更穩定的做法是改用 RecyclerView 搭配橫向 LayoutManager,或乾脆用 GridLayoutManager 直接做表格。
希望本文所述實例對你的 Android 開發有所幫助。
Android Context 完全解析:那些你未必留意的細節
前幾篇寫 ListView 三部曲寫得頗為艱難,內容自認是精華,但不少讀者反饋看不懂。這次換個輕鬆話題,不啃源碼,聊聊大家都熟得不能再熟的 Context。 正因為太常見
Android 嵌套 Fragment 實戰:FrameLayout 外層切模塊、ViewPager 內層切頁籤
前言 之前介紹 ActivityGroup 時,不少人問到嵌套使用的問題。同樣的需求在 Fragment 上自然也會出現,好消息是當時最新的 Android suppor
Android VLC 播放器二次開發:CPU 類型檢查與介面初始化
上一篇講了 VLC 整個程式的模組劃分與介面主要使用的技術,今天來分析 VLC 的初始化過程,重點是介面初始化與解碼庫加載。主要分析 org.videolan.vlc.g
Android RecyclerView 模仿探探左右滑動卡片
這類卡片式左右滑動效果,常用於相簿、履歷、推薦卡片等場景。以 RecyclerView 實作時,可以分成兩個關鍵部分:自定義 LayoutManager 負責卡片堆疊,