如何在到达Android 中的边缘之前动态添加多个按钮以提供行跳转?

How to add many buttons dynamically giving a line jump before arriving at the edge in Android?

我正在尝试将许多按钮添加到 RelativelayoutLinearlayout

布局

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

然后在 class

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

但结果是

一个在另一个上面,但我需要这样的东西:

编辑

如果我使用方向 horizontal 和重力 centerLinearLayout,就会发生这种情况

不要使用 RelativeLayout,而是使用方向为水平的 LinearLayout,并在 运行 时间

在其中添加按钮

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

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

请看这里:Flow layout example

快乐编码:)

您可以使用 griedlayout 来解决您的问题