动态添加多个Button到多个LinearLayout

发布于 2025-01-07 01:30:58 字数 1274 浏览 6 评论 0原文

我想动态添加按钮到不同的 LinearLayout (使用 Java),但在此之前我必须将 LinearLayout 添加到主视图,顺便说一下,它也是一个 LinearLayout

这是我的代码:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    globalLinear = (LinearLayout) findViewById(R.id.viewButtons);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);

    for(int i = 1; i <= nbButton; i++) {
        if(i % 3 == 0) {
             row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
        }
        Button b = new Button(this);
            int number = generator.nextInt(complexity);

            b.setText(number+"");
            row.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT,
                                           LayoutParams.WRAP_CONTENT) );    
    }
}

R.id.viewButtons 是里面的主要(垂直)LinearLayoutR.layout.row_buttons 是水平LinearLayout

正如您在上面所看到的,我尝试使用 (i % 3 == 0) 为每个 LinearLayout 获取 3 个按钮 但似乎从未创建新的 LinearLayout 。

感谢您的帮助 :)

I would like to add buttons to different LinearLayout dynamically (with Java) but before that I have to add LinearLayout to the main View which is also a LinearLayout by the way.

Here is my code:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    globalLinear = (LinearLayout) findViewById(R.id.viewButtons);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);

    for(int i = 1; i <= nbButton; i++) {
        if(i % 3 == 0) {
             row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
        }
        Button b = new Button(this);
            int number = generator.nextInt(complexity);

            b.setText(number+"");
            row.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT,
                                           LayoutParams.WRAP_CONTENT) );    
    }
}

R.id.viewButtons is the main (vertical) LinearLayout inside.
R.layout.row_buttons is a horizontal LinearLayout.

As you can see above, I am trying to get 3 buttons per LinearLayout with (i % 3 == 0)
But it seems new LinearLayout are never created.

Thank you for your help :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽月 2025-01-14 01:30:58

您可能需要定义线性布局,在循环内创建它的新实例,以便只要循环执行就可以创建它。

You might need to define the linear layout, create new instance of it within the loop for it to be created as long as the loop execute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文