动态GridLayout

MDP*_*MDP 11 android

我在另一个班级犯了一个错误,这就是为什么它不起作用.下面的代码似乎是正确的

我正在尝试创建一个动态的GridLayout.在另一个类中,不是这个,我有一个方法来设计我的gridlayout的行和列.在下面的课程中,我为GridLayout添加了一些按钮:

int buttons= 6;//the number of bottons i have to put in GridLayout
int buttonsForEveryRow = 3; // buttons i can put inside every single row
int buttonsForEveryRowAlreadyAddedInTheRow =0; // count the buttons added in a single rows
int columnIndex=0; //cols index to which i add the button
int rowIndex=0; //row index to which i add the button

for(int i=0; i < buttons;i++){          
    /*if numeroBottoniPerRigaInseriti equals numeroBottoniPerRiga i have to put the other buttons in a new row*/
    if(buttonsForEveryRowAlreadyAddedInTheRow ==buttonsForEveryRow ){
        rowIndex++; //here i increase the row index
        buttonsForEveryRowAlreadyAddedInTheRow  =0;  
        columnIndex=0; 
    }   

    Spec row = GridLayout.spec(rowIndex, 1); 
    Spec colspan = GridLayout.spec(columnIndex, 1);
    GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(row, colspan);
    gridLayout.addView(button_to_add,gridLayoutParam);

    buttonsForEveryRowAlreadyAddedInTheRow ++;
    columnIndex++;
Run Code Online (Sandbox Code Playgroud)

在下图中,您可以看到我得到的内容:缺少按钮3和6.我担心我没有GridLayout.spec正常使用.

在此输入图像描述

Aru*_* MG 14

使用下面的代码,您可以使用列跨度和行跨度动态地将图像视图添加到网格布局.

    gridLayout = (GridLayout) findViewById(R.id.gridview);

    gridLayout.removeAllViews();

    int total = 10;
    int column = 3;
    int row = total / column;
    gridLayout.setColumnCount(column);
    gridLayout.setRowCount(row + 1);
    for (int i = 0, c = 0, r = 0; i < total; i++, c++) {
        if (c == column) {
            c = 0;
            r++;
        }
        ImageView oImageView = new ImageView(this);
        oImageView.setImageResource(R.drawable.ic_launcher);            

        oImageView.setLayoutParams(new LayoutParams(100, 100));

        Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
        Spec colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
        if (r == 0 && c == 0) {
            Log.e("", "spec");
            colspan = GridLayout.spec(GridLayout.UNDEFINED, 2);
            rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 2);
        }
        GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
                rowSpan, colspan);
        gridLayout.addView(oImageView, gridParam);


    }
Run Code Online (Sandbox Code Playgroud)

  • 嗨,欢迎来到StackOverflow.请不要只是将代码作为答案发布.解释你的想法,这样我们就能更好地了解你的所作所为.谢谢. (12认同)
  • @ Strive55我不同意.他花时间发布代码,如果你愿意,你可以弄清楚它是如何工作的.这不是一个很大的片段,很容易理解 (11认同)