我试图实现以下编程方式(而不是通过XML声明):
<RelativeLayout...>
<TextView ...
android:id="@+id/label1" />
<TextView ...
android:id="@+id/label2"
android:layout_below: "@id/label1" />
</RelativeLayout>
换句话说,我如何使第二个TextView
出现在第一个TextView
的下面,但我想在代码中做到:
RelativeLayout layout = new RelativeLayout(this);
TextView label1 = new TextView(this);
TextView label2 = new TextView(this);
...
layout.addView(label1);
layout.addView(label2);
setContentView(layout);
谢谢,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);