FOR 循环中不显示的按钮

Buttons not displaying from FOR loop

我一直在尝试根据值列表以编程方式添加按钮。

问题:只生产了一个按钮,而不是一系列。此按钮包含数组中最后一个值的信息。

我收集了一个名为 'values' 的值数组,然后使用 for 循环添加按钮。

这是我添加按钮的循环代码:

    public void updateButtons(List<String> values, View rootView) {

    //Find relative layout
    RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.RelativeLayoutManage);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    params.setMargins(50, 10, 50, 10);

    for (String mTrip : values) {

        //New button
        Button Postbtn = new Button(mContext);

        //Style
        Postbtn.setBackgroundResource(R.drawable.buttonshape);
        Postbtn.setTextColor(getResources().getColor(R.color.DarkGreen));
        Postbtn.setTextSize(25);

        //set text
        Postbtn.setText(mTrip.toString());

        //set id
        Postbtn.setId(i);
        int id_ = Postbtn.getId();

        //Add to view
        rl.addView(Postbtn, params);
        Postbtn = ((Button) rootView.findViewById(id_));

        //Add listener
        Postbtn.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {

                Log.v("TripNumber", Integer.toString(i));
                //TODO: Change Fragment
            }
        });
        i++;
    }
    }

如果需要还有我对应的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayoutManage"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>

似乎它们可能相互重叠。您需要使用 LinearLayout

<LinearLayout android:id="@+id/RelativeLayoutManage"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    />

您正在将 Button 添加到 RelativeLayout。在您当前的代码中,所有按钮都存在,但一个位于其他按钮之上。您应该制作一个 below/above 其他按钮以使所有按钮可见。否则使用 LinearLayout

我通过在添加到布局中时定位每个按钮解决了这个问题。只需使用:

params.addRule(RelativeLayout.BELOW, Postbtn.getId() - 1);
Postbtn.setLayoutParams(params);