我从代码实现相对布局时遇到了问题。 我想要的是,TextView1位于左侧,TextView2位于屏幕右侧一行。Programmatic RelativeLayout重叠
它从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);
但是这将很好地工作:(与WRAP_CONTENT
替换MATCH_PARENT
):
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);
可能我的帖子在这里可以帮助您:http://stackoverflow.com/a/12524612/1306012 –