如何编程的几行一个按钮添加到布局呢? [英] How do I programmatically add buttons into layout one by one in several lines?

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

问题描述

如何创建按钮一一几行列表? 我做这样的:

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);
    }

和得到了只有一行:


如何进入下一行编程?


How to go to the next line programmatically?

推荐答案

的问题是,你的按钮不会自动换到屏幕的下一部分。你必须明确告诉机器人如何你想你的意见进行定位。为此,您使用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 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);
}

我假设 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。一旦所有的按键都加入,该行被添加到您的活动的布局。然后它重复。这仅仅是一些伪code,但它可能会工作。

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...

<一个href="http://stackoverflow.com/questions/how-to-ask">http://stackoverflow.com/questions/how-to-ask

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

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