«

GridLayout绘制复杂表格

时间:2024-3-2 18:16     作者:韩俊     分类: Android


项目要求在Android页面绘制复杂表格,有跨行跨列的需求。表格数据来自于服务器,每个单元格对应相关数据:序号(index)、行号(row)、列号(col)、跨行数(rowSpan)、跨列数(colSpan)等。


实际表格如下:


由于有跨行跨列,序号不规则,容易出现画了A行后,B行的相应列数已经被占用,因此需要判断。方法是:将表格抽象为二位数组,当跨行是,标记占用的其他行的空格;在绘制是首先判断这个单元格是否被占用,如果占用,二位数组的列号加1,直到空位出现。

int row = 0;
int rowSpan = 0;
int colSpan = 0;
int lastRow = 0;
int maxCols = 0;
int colCount = 0;
int windowWidth = 获取屏幕宽度;
int colWidth = 0;
int index = 0;
View view = null;

List<Integer> filledCellList = new ArrayList<Integer>();

do {

    row = ...;
    rowSpan = ...;
    colSpan = ...;
    maxCols = ...;

    GridLayout gridLayout = new GridLayout(context);
    gridLayout.setColumnCount(newMaxCols);
    gridLayout.setUseDefaultMargins(true);
    gridLayout.setOrientation(GridLayout.HORIZONTAL);
    gridLayout.setBackgroundResource(R.color.dark_green);
    gridLayout.setAlignmentMode(GridLayout.ALIGN_MARGINS);
    colWidth = windowWidth / maxCols;

    if (row > lastRow) {
    <span style="white-space:pre">  </span>lastRow = row;
        colCount = 1;
    }

    view = createView(...);

    if (view != null) {
        view.setBackgroundColor(Color.WHITE);

        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.setMargins(1, 1, 1, 1);
        params.width = colWidth * colSpan;

        index = maxCols * (row - 1) + colCount - 1;

        while (filledCellList.contains(index)) {
            colCount++;
            index = maxCols * (row - 1) + colCount - 1;
        }

        if (rowSpan > 1) {

            for (int j = row; j < row + rowSpan; j++) {
                for (int i = colCount; i < colCount + colSpan; i++) {
                    if (j == row && i == colCount) {
                        continue;
                    }
                    index = maxCols * (j - 1) + i - 1;
                    filledCellList.add(index);
                }
            }
        }

        params.columnSpec = GridLayout.spec(colCount - 1, colSpan, GridLayout.FILL);
        params.rowSpec = GridLayout.spec(row - 1, rowSpan, GridLayout.FILL);
        gridLayout.addView(view, params);

        colCount += colSpan;
    }

} while (cursor.moveToNext()); //一个Cursor数据代表一个单元格数据

最终将GridLayout加入到ScrollView,实现滑动显示。

标签: android

热门推荐