【问题标题】:GridLayout - removing spaces between cellsGridLayout - 删除单元格之间的空格
【发布时间】:2015-11-06 11:28:16
【问题描述】:

我正在尝试创建一个包含 16 x 16 按钮的 GridLayout,但我无法删除按钮之间的空格。

我看到了this,但没用。

这是我现在正在尝试的:

public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
    GridLayout v = (GridLayout)findViewById(R.id.myGrid);
    v.setPadding(0, 0, 0, 0);
    v.setUseDefaultMargins(false);
    v.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
    v.setRowOrderPreserved(false);
    Random r = new Random();
    for (int row = 0; row < 16; row++)
        for (int col = 0; col < 16; col++) {
            GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
            lp.setMargins(0, 0, 0, 0);
            lp.rowSpec = GridLayout.spec(row);
            lp.columnSpec = GridLayout.spec(col);
            lp.width = 40;
            lp.height = 40;
            Button b = new Button(this);
            b.setWidth(40);
            b.setHeight(40);
            b.setText(Integer.toString(r.nextInt(10)));
            b.setPadding(0, 0, 0, 0);
            b.setLayoutParams(lp);
            v.addView(b, lp);
        }
}

截图

知道有什么问题吗?

编辑:我将一些按钮的背景更改为绿色图片,这就是我得到的:

Doh!

显然间距是按钮图像的一部分...为什么是 Android,为什么?

【问题讨论】:

    标签: android spacing android-gridlayout


    【解决方案1】:

    因为你期望每个item都有固定的宽度和固定的高度,所以这里就出错了。试试这个:

    GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
                lp.setMargins(0, 0, 0, 0);
                lp.rowSpec = GridLayout.spec(row);
                lp.columnSpec = GridLayout.spec(col);
                //lp.width = 40;
                //lp.height = 40;
                Button b = new Button(this);
                //b.setWidth(40);
                //b.setHeight(40);
                b.setText(Integer.toString(r.nextInt(10)));
                b.setPadding(0, 0, 0, 0);
                b.setLayoutParams(lp);
                v.addView(b, lp);
    }
    

    【讨论】:

    • 我找不到构造函数 GridLayout.LayoutParams(int, int),但评论“lp.width = 40”甚至将其设置为 GridLayout.LayoutParams.WRAP_CONTENT 对我不起作用。
    • 这个想法是你尝试为按钮设置固定的高度和宽度,所以它出错了。我没有尝试过,但您可以删除所有固定的高度和宽度。请查看我编辑的答案。
    猜你喜欢
    • 2014-02-22
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多