0

通过从代码实现相对布局,我遇到了问题。我想要的是,TextView1 位于左侧,TextView2 位于屏幕右侧一行。

它在 XML 中运行良好,但从代码中执行此操作却没有……可能是什么原因?

这项工作很好:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="TextView" />

</RelativeLayout>

这不起作用(给出元素重叠):

RelativeLayout rel = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);
rel.setLayoutParams(params);

TextView t1 = new TextView(this);   
t1.setText("balbla_1");
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
t1.setLayoutParams(lp1);

TextView t2 = new TextView(this);
t2.setText("balbla_2");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
t2.setLayoutParams(lp2);        

rel.addView(t1);
rel.addView(t2);

setContentView(rel);

但这可以正常工作:(替换MATCH_PARENTWRAP_CONTENT):

RelativeLayout rel = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);
rel.setLayoutParams(params);

TextView t1 = new TextView(this);   
t1.setText("balbla_1");
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
t1.setLayoutParams(lp1);

TextView t2 = new TextView(this);
t2.setText("balbla_2");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
t2.setLayoutParams(lp2);        

rel.addView(t1);
rel.addView(t2);

setContentView(rel);
4

1 回答 1

1

Java 代码与 XML 不完全匹配,重叠是因为您忘记了:

lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

你也忽略了:

lp1.addRule(RelativeLayout.CENTER_VERTICAL);

而且您使用MATCH_PARENT的是宽度而不是WRAP_CONTENT.

于 2012-12-16T20:08:32.713 回答