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

用 ListView 打造自定義表格:動態列、單元格合並與自定義鍵盤

編輯:關於 Android 程式設計

要解決的三個問題

1. 列數不固定:根據數據源動態生成不同列數;

2. 支持按數據定義合並單元格;

3. 可填寫的單元格能自由選擇自定義鍵盤或系統鍵盤。

圍繞這三點做了一個簡陋實現,核心源碼如下(它只是主界面的一部分,不方便放完整 Demo)。

自定義適配器

CallBackInterface 是自定義回調接口,之所以需要回調,是因為用戶輸入時要及時回寫數據。

public class SiteDetailViewAdapter extends BaseAdapter implements CallBackInterface {
    private Context context;
    private LayoutInflater inflater;
    private ArrayList<HashMap<String,Object>> lists;
    private KeyBoard keyBoard = null;      // 自定義鍵盤
    private ListView listView = null;
    private boolean isReadOnly = false;    // 是否瀏覽狀態
    private String[] arrCellType = null;
    private int[] arrHeadWidth = null;     // 每列寬度

    public SiteDetailViewAdapter(Context context,
            ArrayList<HashMap<String,Object>> lists, KeyBoard keyBoard,
            ListView listView, boolean isReadOnly, int[] arrHeadWidth) {
        this.context = context;
        this.lists = lists;
        inflater = LayoutInflater.from(context);
        this.keyBoard = keyBoard;
        this.listView = listView;
        this.isReadOnly = isReadOnly;
        this.arrHeadWidth = arrHeadWidth;
        this.listView.setAdapter(this);
    }

    @Override public int getCount() { return lists.size(); }
    @Override public Object getItem(int arg0) { return arg0; }
    @Override public long getItemId(int arg0) { return arg0; }

    @Override
    public View getView(int index, View view, ViewGroup arg2) {
        HashMap map = lists.get(index);
        String type = (String) map.get("rowtype");

        ArrayList<ItemCell> itemCells = new ArrayList();
        // 序號列
        itemCells.add(new ItemCell((index + 1) + "", "-1", 1, -1, 1));
        for (int i = 0; i < map.size() - 1; i++) {
            itemCells.add((ItemCell) map.get(i + ""));
        }

        // 複用時需額外判斷行類型,類型不同則不能複用
        if (view == null
                || view != null && !((ListItemCustom) view.getTag()).getType().equals(type)) {
            view = inflater.inflate(R.layout.customel_list_item, null);
            ListItemCustom itemCustom = (ListItemCustom) view.findViewById(R.id.custome_item);
            itemCustom.buildItem(type, context, isReadOnly, arrHeadWidth,
                                 itemCells, index, this.listView, this.keyBoard, this);
            view.setTag(itemCustom);
        } else {
            ListItemCustom itemCustom = (ListItemCustom) view.getTag();
            itemCustom.refreshData(itemCells, index);
        }

        // 隔行變色
        view.setBackgroundColor(index % 2 == 0
            ? Color.argb(250, 255, 255, 255)
            : Color.argb(250, 224, 243, 250));
        return view;
    }

    @Override
    public boolean exectueMethod(Object params) {
        String[] arr = (String[]) params;
        HashMap map = lists.get(Integer.parseInt(arr[0]));
        ItemCell itemCell = (ItemCell) map.get(arr[1]);
        itemCell.setCellValue(arr[2]);
        itemCell.setIsChange(true);
        return false;
    }
}

行布局控件

ListItemCustom 繼承 LinearLayout,負責一行內多個單元格的排列。原文註釋中提到代碼有冗余,Demo 優先保證效果、未做重構。

這裡有一個必須注意的坑:不要把每行的 Map 直接傳進 ListItemCustom 去取值或回寫。因為 Map 傳的是引用,再疊加 ListView 的複用繪制機制,最終拿到的 Map 並不是你期望的那一份。所以實現中改用了 ItemCell 列表 + 回調接口的方式。

public class ListItemCustom extends LinearLayout {
    private String type = "-1";
    private Context context = null;
    private boolean isRead = false;
    private int[] headWidthArr = null;
    private ListView listView = null;
    private KeyBoard keyBoard = null;
    private int rowNum = -1;
    private ArrayList<View> viewList = new ArrayList();
    private CallBackInterface callBack = null;

    public ListItemCustom(Context context) { super(context); }
    public ListItemCustom(Context context, AttributeSet attrs) { super(context, attrs); }

    public void buildItem(String type, Context context, boolean isRead, int[] headWidthArr,
            ArrayList<ItemCell> itemCells, int rowNum, ListView listView,
            KeyBoard keyBoard, CallBackInterface callBack) {
        this.context = context;
        this.isRead = isRead;
        this.headWidthArr = headWidthArr;
        this.setOrientation(LinearLayout.VERTICAL);
        this.rowNum = rowNum;
        this.listView = listView;
        this.keyBoard = keyBoard;
        this.callBack = callBack;
        this.type = type;
        this.setLayoutParams(new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, 45));
        this.addCell(itemCells);
    }

    /** 複用時只刷新數據,不重複構建 */
    public void refreshData(ArrayList<ItemCell> itemCells, int rowNum) {
        this.rowNum = rowNum;
        this.refreshCells(itemCells);
    }

    private void refreshCells(ArrayList<ItemCell> itemCells) {
        for (int i = 0; i < itemCells.size(); i++) {
            ItemCell itemCell = itemCells.get(i);
            if (itemCell.getCellType() == ItemCellValueType.VALUE_NONE) {
                TextView view = (TextView) viewList.get(i);
                view.setId(itemCell.getCellId());
                view.setText(itemCell.getCellValue());
            } else {
                EditText view = (EditText) viewList.get(i);
                view.setId(itemCell.getCellId());
                view.setText(itemCell.getCellValue());
                this.setEditView(view, itemCell.getCellKey());
                if (itemCell.getCellType() == ItemCellValueType.VALUE_NUMBER) {
                    this.setOnKeyBorad(view, itemCell.getCellInRow());
                }
            }
        }
    }

    /** 根據 span 累加列寬,實現合並 */
    private int getCellWidth(int cellStart, int cellEnd) {
        int width = 0;
        for (int i = cellStart; i < cellEnd; i++) {
            width = this.headWidthArr[i] + width;
        }
        return width;
    }

    private void addCell(ArrayList<ItemCell> itemCells) {
        LinearLayout secondLayout = new LinearLayout(context);
        secondLayout.setOrientation(LinearLayout.HORIZONTAL);
        secondLayout.setLayoutParams(new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        this.addView(secondLayout);

        int cellIndex = 0;
        for (int i = 0; i < itemCells.size(); i++) {
            ItemCell itemCell = itemCells.get(i);
            int endIndex = cellIndex + itemCell.getCellSpan();
            int width = getCellWidth(cellIndex, endIndex);
            cellIndex = endIndex;

            if (itemCell.getCellType() == ItemCellValueType.VALUE_NONE) {
                TextView view = (TextView) getReadView();
                view.setId(itemCell.getCellId());
                view.setText(itemCell.getCellValue());
                view.setWidth(width);
                secondLayout.addView(view);
                viewList.add(view);
            } else {
                EditText view = (EditText) getInputView();
                view.setId(itemCell.getCellId());
                view.setText(itemCell.getCellValue());
                view.setWidth(width);
                this.setEditView(view, itemCell.getCellKey());
                if (itemCell.getCellType() == ItemCellValueType.VALUE_NUMBER) {
                    this.setOnKeyBorad(view, itemCell.getCellInRow());
                }
                secondLayout.addView(view);
                viewList.add(view);
            }

            // 單元格之間加分隔豎線
            if (i != itemCells.size() - 1) {
                secondLayout.addView(getVerticalLine());
            }
        }
    }

    private View getVerticalLine() {
        return LayoutInflater.from(context).inflate(R.layout.atom_line_v_view, null);
    }
    private View getReadView() {
        return LayoutInflater.from(context).inflate(R.layout.atom_text_view, null);
    }
    private View getInputView() {
        return LayoutInflater.from(context).inflate(R.layout.atom_edttxt_view, null);
    }

    /** 計算某行在屏幕上的 Y 坐標,供自定義鍵盤定位 */
    private int[] getYPos(ListView listview, int index) {
        int[] yPosArr = new int[2];
        Rect r = new Rect();
        listview.getChildAt(0).getGlobalVisibleRect(r);
        int first = listview.getFirstVisiblePosition();
        yPosArr[1] = (index - first + 1) * r.height() + listview.getTop();
        yPosArr[0] = (index - first) * r.height() + listview.getTop();
        return yPosArr;
    }

    private void setOnKeyBorad(EditText edtText1, int index) {
        if (!this.isRead) {
            onListenText(edtText1, this.listView, index);
        }
    }

    private void onListenText(EditText edtText, ListView listView, int index) {
        final ListView lsv = listView;
        final int idx = index;
        edtText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                if (arg1) {
                    int[] y = getYPos(lsv, idx);
                    keyBoard.show((EditText) arg0, y[0], y[1]);
                }
            }
        });
    }

    /** 輸入即回寫,通過回調把 rowNum + key + value 傳給 Adapter */
    private void setEditView(EditText edtText1, final String key) {
        if (this.isRead) {
            edtText1.setEnabled(false);
        } else {
            edtText1.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable arg0) {
                    String[] arr = new String[3];
                    arr[0] = rowNum + "";
                    arr[1] = key;
                    arr[2] = arg0.toString();
                    callBack.exectueMethod(arr);
                }
                @Override public void beforeTextChanged(CharSequence arg0, int a, int b, int c) { }
                @Override public void onTextChanged(CharSequence arg0, int a, int b, int c) { }
            });
        }
    }

    public String getType() { return this.type; }
}

單元格模型

ItemCell 封裝了單個格子的值、類型、跨列數(span)、列內序號等信息,是整個表格的數據基石。

public class ItemCell {
    private String cellValue = "";
    private int cellSpan = 1;          // 跨幾列
    private String cellKey = "";
    private int cellInRow = 0;         // 行內第幾個可輸入項
    private long cellType = ItemCellValueType.VALUE_NONE;
    private int colNum = 0;
    private int rowType = 0;
    private int cellId = -1;
    private boolean isValueFromTable = false;
    private boolean isChange = false;

    public ItemCell(String cellValue, String cellKey, long cellType,
                    int cellInRow, int cellSpan) {
        this.cellValue = cellValue;
        this.cellType = cellType;
        this.cellSpan = cellSpan;
        this.cellKey = cellKey;
        this.cellInRow = cellInRow;
    }

    public ItemCell(String cellValue, String cellKey, long cellType, int cellInRow) {
        this(cellValue, cellKey, cellType, cellInRow, 1);
    }
    // getter / setter 省略
}

行布局 XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:orientation="vertical"
    android:id="@+id/test_dajej"
    android:background="#ffffff">

    <srit.collection.widget.costomtable.ListItemCustom
        android:id="@+id/custome_item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

列合並的思路是累加 cellSpan 對應的列寬;行合並同理,只需在自定義布局中多嵌套一層 LinearLayout 並調整 span 即可。

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