如何以编程方式在 RelativeLayout 中布置视图? [英] How to lay out Views in RelativeLayout programmatically?

查看:35
本文介绍了如何以编程方式在 RelativeLayout 中布置视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式(而不是通过 XML 以声明方式)实现以下目标:

I'm trying to achieve the following programmatically (rather than declaratively via XML):

<RelativeLayout...>
   <TextView ...
      android:id="@+id/label1" />
   <TextView ...
      android:id="@+id/label2"
      android:layout_below: "@id/label1" />
</RelativeLayout>

换句话说,如何让第二个 TextView 出现在第一个下面,但我想在代码中做到这一点:

In other words, how do I make the second TextView appear below the first one, but I want to do it in code:

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"重叠.我做错了什么?

Update:

Thanks, TreeUK. I understand the general direction, but it still doesn't work - "B" overlaps "A". What am I doing wrong?

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);

推荐答案

根据我已经能够拼凑的内容,您必须使用 LayoutParams 添加视图.

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

所有功劳都归功于 sechastain,要以编程方式相对定位您的项目,您必须为它们分配 id.

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

然后 addRule(RelativeLayout.RIGHT_OF, tv1.getId());

这篇关于如何以编程方式在 RelativeLayout 中布置视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆