反转Androids GridLayout中的行排序

时间:2017-04-20 12:16:48

标签: java android

我正在使用一个以编程方式填充的GridLayout。布局中的子项填充如下:

0 1 2

3 4 5

6 7 8

我希望它像:

6 7 8

3 4 5

0 1 2

有一种简单的方法吗?

这是我的代码:

GridLayout layout = (GridLayout) view.findViewById(R.id.grid_layout);

    layout.setColumnCount(Chess.NUM_OF_COLS);
    layout.setRowCount(Chess.NUM_OF_ROWS);
    GridLayout.spec(0, 63);

    for(int x = 0; x < Chess.NUM_OF_COLS ; x++){
        for(int y = 0; y < Chess.NUM_OF_ROWS; y++){
            int finalX = x;
            int finalY = y;
            ImageView squareImageView = new ImageView(getContext());
            squareImageView.setImageResource(R.drawable.square);
            squareImageView.setColorFilter(Chess.isWhiteSquare(Chess.coorToSqi(finalX, finalY)) ?
                    Color.WHITE : Color.BLACK, PorterDuff.Mode.SRC_ATOP);
            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
            param.height = GridLayout.LayoutParams.WRAP_CONTENT;
            param.width = GridLayout.LayoutParams.WRAP_CONTENT;
            param.setGravity(Gravity.CENTER);
            param.columnSpec = GridLayout.spec(finalX);
            param.rowSpec = GridLayout.spec(finalY);
            squareImageView.setLayoutParams(param);

            squareImageView.setOnClickListener(onSquareClick(finalX, finalY, layout));
            layout.addView(squareImageView);
        }
    }

1 个答案:

答案 0 :(得分:0)

问题与UI组件无关,因此我们将重点介绍如何填充2x2矩阵。

我们需要从最大值填充到最小值,列号需要从最高列号而不是0开始。

e.g。

matrix[0][2]
matrix[0][1]
matrix[0][0]
matrix[1][2]

......等等

以下是执行该操作的算法:

   public void test(){
        int rows = 3;
        int cols = 3;
        int[][] rowsColumns = new int[rows][cols];
        int max = rows * cols - 1;
        for(int i = 0; i < cols; i++){
            for(int j = rows-1; j >= 0; j--){
                rowsColumns[i][j] = max--;
            }
        }
    for(int i = 0; i < cols; i++){
        for(int j = 0; j < rows; j++){
            System.out.print(rowsColumns[i][j]);
        }
        System.out.println();
    }

    }

请注意,我们从最高潜在值开始,因为它们是顺序的,并且只是递减内循环的每次迭代。这给了我们以下输出:

678
345
012