android编程布局

android编程布局,android,android-layout,Android,Android Layout,我正在android中构建一个简单的两列列表,需要动态填充行数。xml布局工作正常,但当我尝试以编程方式构建布局时,第二列不会显示。有什么想法吗 private void addRow(String text, String value) { RelativeLayout line = new RelativeLayout(this); line.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.Lay

我正在android中构建一个简单的两列列表,需要动态填充行数。xml布局工作正常,但当我尝试以编程方式构建布局时,第二列不会显示。有什么想法吗

private void addRow(String text, String value) {
    RelativeLayout line = new RelativeLayout(this);

    line.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));

    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    rlp.addRule(RelativeLayout.CENTER_VERTICAL);

    line.setPadding(0, 0, 0, 15);

    TextView caption = new TextView(this);
    caption.setLayoutParams(rlp);
    caption.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
    caption.setText(text);

    rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    rlp.addRule(RelativeLayout.CENTER_VERTICAL);

    TextView val = new TextView(this);
    val.setLayoutParams(rlp);
    val.setTextColor(0x05b4e4);
    val.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
    val.setText(value);

    line.addView(caption);
    line.addView(val);

    mLayout.addView(line);
}
一行(有效的)可比较的xml是


再次-行填充,但第二列不可见。下面是它的内容:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/scrollViewRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:keepScreenOn="true">

<LinearLayout
    android:id="@+id/viewRoot"
    android:paddingTop="20px"
    android:paddingBottom="40px"
    android:paddingLeft="20px"
    android:paddingRight="20px"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

</LinearLayout>

</ScrollView>

要添加的视图的布局参数应为LinearLayout.LayoutParams类型,因为父视图将为该类型

这条线

line.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
应该成为

line.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,  LinearLayout.LayoutParams.WRAP_CONTENT));


然而,我认为这应该会导致一个例外

相对年轻的孩子拥有唯一的非零id是很重要的

在API 17+上,您可以使用

myView.setId(View.generateViewId());

或者,如果您必须支持较旧的API级别,则可以使用(并每次递增)一个简单的静态AtomicInteger值。

无效。尝试将AtomicInteger设置为
Integer.MAX_VALUE-1000
,但没有效果。您是对的,应该是这样的。不幸的是,它没有解决问题。
myView.setId(View.generateViewId());