如何在每行中添加3个按钮

时间:2018-09-01 17:26:02

标签: java android

我想在每行中添加3个按钮,就像通过动态方式创建的ROW一样。我尝试了以下方式,但每行显示一个按钮。

 LinearLayout ll_rootOBJ = findViewById(R.id.ll_root);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);

        int total_items=13;
        for (int k=0; k<total_items; k++)
        {
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setTag(k);

            Button b = new Button(this);
            b.setTag(k);
            b.setText("Button " + k);
            ll.addView(b);
            mainLayout.addView(ll);
        }

        ll_rootOBJ.addView(mainLayout);

任何帮助都会有用。谢谢。

3 个答案:

答案 0 :(得分:1)

只需在另一个 for 循环中将两个按钮添加到“ LinearLayout ll”视图中

答案 1 :(得分:0)

解决方案:

    LinearLayout ll_rootOBJ = findViewById(R.id.ll_root);
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);

    for (int k=0; k<13; k++)
    {
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(k);

        for (int i=1; i<4; i++) {
            Button b = new Button(this);
            b.setTag(k);
            b.setText("Button");
            ll.addView(b);
        }
        mainLayout.addView(ll);

    }

    ll_rootOBJ.addView(mainLayout);

这将完全提供您想要的。快乐编码。

enter image description here

这是您想要的吗? (在图片中)

答案 2 :(得分:0)

一个简单的答案是在每次迭代中仅添加3个按钮。我认为这是最后一次迭代,添加的按钮更少了,只需添加更少的内容即可:

    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);

    int totalItems = 13;
    for (int k=0; k<totalItems; k+=3)
    {
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        layout.setTag(k/3);

        int numberOfButtonsInRow = (k + 3 < totalItems) ? 3 : totalItems % 3;

        for(int l = 0; l < numberOfButtonsInRow; l++)
        {
            Button b = new Button(this);
            b.setTag(k + l);
            b.setText("Button " + (k + l));
            layout.addView(b);
        }

        mainLayout.addView(layout);
    }

我也建议将内部循环的内容提取到一个单独的函数中,尽管我在这里将其简化了。