如何以编程方式将按钮逐行添加到几行中?

Svi*_*lav 21 android button

如何在几行中逐个创建按钮列表?我做的:

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);
    }
Run Code Online (Sandbox Code Playgroud)

并且只有一行:

我懂了
如何以编程方式进入下一行?

b_y*_*yng 40

问题是您的按钮不会自动换行到屏幕的下一部分.您必须具体告诉Android您希望如何定位视图.您可以使用诸如LinearLayout或RelativeLayout之类的ViewGroup来完成此操作.

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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


Voi*_*ode 8

这就像一个答案,但不需要制作XML文件.

public class mainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        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 LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

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

            layout.addView(row);
        }
        setContentView(layout);
        //setContentView(R.layout.main);
    }
} 
Run Code Online (Sandbox Code Playgroud)