GridLayout(不是GridView):尝试均匀拉伸时,项目未正确定位在GridLayout中

时间:2017-03-09 11:40:34

标签: android grid-layout

我尝试将12个按钮添加到具有固定宽度和高度的3X4 GridLayout中。

所有这些按钮应该在网格内均匀拉伸,但在我调整GridLayout的宽度时,它在某些情况下不能很好地工作。

似乎宽度必须设置为大于某个值,以便可以正确定位所有按钮。

这是我的代码:

        gridLayout = new GridLayout(this);
        gridLayout.setBackgroundColor(Color.RED);
        //width c 
        gridLayout.setLayoutParams(new ViewGroup.LayoutParams(200, 300));
        gridLayout.setRowCount(NUM_OF_ROW);
        gridLayout.setColumnCount(NUM_OF_COL);
        gridLayout.setUseDefaultMargins(false);
        for(int i = 0;i < NUM_OF_ROW; ++i){
            for(int j = 0;j < NUM_OF_COL; ++j){
                Button btn = new Button(this);

                gridLayout.addView(btn);

                GridLayout.LayoutParams params = (GridLayout.LayoutParams) btn.getLayoutParams();

                GridLayout.Spec rowSpec = GridLayout.spec(i,1,1);
                GridLayout.Spec colSpec = GridLayout.spec(j,1,1);
                params.rowSpec = rowSpec;
                params.columnSpec = colSpec;

                params.setGravity(Gravity.FILL);  
                btn.setLayoutParams(params);
            }
        }
        relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
        relativeLayout.addView(gridLayout);

宽度值设置得足够小时会出现问题。

Output I expected
Firebase Documentation

0 个答案:

没有答案