通过从代码实现相对布局我遇到了问题。 我想要的是,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_PARENT
替换为WRAP_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);
答案 0 :(得分:1)
Java代码与XML不完全匹配,重叠是因为您忘记了:
lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
你也忽略了:
lp1.addRule(RelativeLayout.CENTER_VERTICAL);
您使用MATCH_PARENT
代替WRAP_CONTENT
。