如何以编程方式将按钮在多行中一一添加到布局中? [英] How do I programmatically add buttons into layout one by one in several lines?

查看:19
本文介绍了如何以编程方式将按钮在多行中一一添加到布局中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在多行中一一创建按钮列表?我做的:

How to create a list of buttons one by one in several lines? I made this:

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
    for (int i = 1; i < 10; i++) {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + i);
        btnTag.setId(i);
        layout.addView(btnTag);
        ((Button) findViewById(i)).setOnClickListener(this);
    }

并且只有一行:


如何以编程方式转到下一行?

推荐答案

问题是您的按钮不会自动换行到屏幕的下一部分.您必须明确告诉 Android 您希望如何定位您的视图.您可以使用 ViewGroups(例如 LinearLayout 或 RelativeLayout)来执行此操作.

The issue is that your buttons are not going to automatically wrap to the next part of the screen. You have to specifically tell Android how you want your Views to be positioned. You do this using ViewGroups such as LinearLayout or RelativeLayout.

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

        for (int i = 0; i < 3; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        for (int j = 0; j < 4; j++) {
            Button btnTag = new Button(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            btnTag.setText("Button " + (j + 1 + (i * 4)));
            btnTag.setId(j + 1 + (i * 4));
            row.addView(btnTag);
        }

        layout.addView(row);
    }

我假设 R.id.linear_layout_tags 是此活动的 XML 的父 LinearLayout.

I'm assuming that R.id.linear_layout_tags is the parent LinearLayout of your XML for this activity.

基本上你在这里做的是你正在创建一个 LinearLayout,它将是一行来容纳你的四个按钮.然后添加按钮,并为每个按钮分配一个数字作为它们的 id.添加所有按钮后,该行将添加到您的活动布局中.然后它重复.这只是一些伪代码,但它可能会起作用.

Basically what you're doing here is you're creating a LinearLayout that will be a row to hold your four buttons. Then the buttons are added and are each assigned a number incrementally as their id. Once all of the buttons are added, the row is added to your activity's layout. Then it repeats. This is just some pseudo code but it will probably work.

哦,下次一定要花更多的时间在你的问题上......

Oh and next time be sure to spend more time on your question...

https://stackoverflow.com/questions/how-to-ask

这篇关于如何以编程方式将按钮在多行中一一添加到布局中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆