小编Dan*_*Dan的帖子

如何以编程方式在RelativeLayout中布局视图?

我试图以编程方式实现以下(而不是通过XML声明):

<RelativeLayout...>
   <TextView ...
      android:id="@+id/label1" />
   <TextView ...
      android:id="@+id/label2"
      android:layout_below: "@id/label1" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

换句话说,如何使第二个TextView出现在第一个下面,但我想在代码中执行:

RelativeLayout layout = new RelativeLayout(this);
TextView label1 = new TextView(this);
TextView label2 = new TextView(this);
...
layout.addView(label1);
layout.addView(label2);
setContentView(layout);
Run Code Online (Sandbox Code Playgroud)

更新:

谢谢,TreeUK.我理解大方向,但它仍然不起作用 - "B"重叠"A".我究竟做错了什么?

RelativeLayout layout = new RelativeLayout(this);
TextView tv1 = new TextView(this);
tv1.setText("A");

TextView tv2 = new TextView(this);
tv2.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

layout.addView(tv1);        
layout.addView(tv2, lp);
Run Code Online (Sandbox Code Playgroud)

android android-layout android-view android-relativelayout

231
推荐指数
5
解决办法
19万
查看次数