GridLayout (not GridView) how to stretch all children evenly

后端 未结 20 2147
独厮守ぢ
独厮守ぢ 2020-11-22 09:35

I want to have a 2x2 grid with a buttons inside. This is only ICS so I am trying to use the new GridLayout given.

Here\'s the XML of my layout:

 <         


        
20条回答
  •  眼角桃花
    2020-11-22 10:19

    Result :

    Try something like this :

        final int MAX_COLUMN = gridView.getColumnCount(); //5
        final int MAX_ROW = gridView.getRowCount(); //7
        final int itemsCount = MAX_ROW * MAX_COLUMN; //35
    
        int row = 0, column = 0;
    
        for (int i = 0; i < itemsCount; i++) {
            ImageView view = new ImageView(this);
    
            //Just to provide alternate colors
            if (i % 2 == 0) {
                view.setBackgroundColor(Color.RED);
            } else {
                view.setBackgroundColor(Color.GREEN);
            }
    
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(row, 1F), GridLayout.spec(column, 1F));
            view.setLayoutParams(params);
            gridView.addView(view);
    
            column++;
    
            if (column >= MAX_COLUMN) {
                column = 0;
                row++;
            }
        }
    

    If you want specific width and height for your cells, then use :

         params.width = 100; // Your width
         params.height = 100; //your height
    

提交回复
热议问题