如何动态添加许多按钮,在到达Android边缘之前进行线条跳转?

时间:2015-02-14 03:59:53

标签: android android-button android-relativelayout

我正在尝试向RelativelayoutLinearlayout添加许多按钮,

布局

<Relativelayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            >
</Relativelayout>

然后在课堂上

_ll_layout = (RelativeLayout) findViewById(R.id.container);

我只知道如何使用代码动态添加按钮。

JSONArray jsonArray = new JSONArray(tmp.getString("productos"));
Button bt[] = new Button[jsonArray.length()]; // size of product
for (int i = 0; i < jsonArray.length(); i ++){
    int padding_40dp = (int) (40 * scale + 0.5f);
    int margin_10dp = (int) (10 * scale + 0.5f);
    int padding_90dp = (int) (90 * scale + 0.5f);
    LinearLayout.LayoutParams params = new Relativelayout.LayoutParams(padding_90dp, padding_40dp);
    params.setMargins(margin_10dp, 0 , 0, 0);
    bt[i] = new Button(DetalleServicioActivity.this);
    bt[i].setText(jsonArray.getJSONObject(i).getString("nombre"));
    bt[i].setTag(new TagInfo(jsonArray.getJSONObject(i).getString("id_producto")));
    bt[i].setTextColor(Color.parseColor("#FFFFFF"));
    bt[i].setBackgroundColor(Color.parseColor("#D8D8D8"));
    bt[i].setEnabled(false);
    bt[i].setId(Integer.parseInt(jsonArray.getJSONObject(i).getString("id_producto")));
    bt[i].setLayoutParams(params);
    _ll_layout.addView(bt[i]);
} 

但结果是

enter image description here

一个接一个,但我需要这样的东西:

enter image description here

修改

如果我使用方向LinearLayout和重力horizontal的{​​{1}},则会发生这种情况

enter image description here

3 个答案:

答案 0 :(得分:3)

我宁愿建议您创建自定义Relative Layout,而不是使用Linear Layoutflow layout。自定义流程布局会相应地调整行视图中的子视图,并会在新行中跳转按钮根据屏幕宽度。

请在这里查看:Flow layout example

快乐编码:)

答案 1 :(得分:0)

使用LinearLayout而不是RelativeLayout,使用方向为水平的LinearLayout,并在运行时添加按钮

根据您的设计要求,请确保此处有两个线性布局。

答案 2 :(得分:0)

您可以使用griedlayout来解决问题