我一直在寻找这个问题的答案。我是Android的新手,并尝试通过java而不是xml以编程方式将项目添加到相对布局。我已经创建了一个测试类来尝试它,但项目保持堆叠而不是正确格式化。我现在只想在另一个下面使用一个TextView(最终我将使用参数的左侧和右侧,但我开始很简单。我缺少什么?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
RelativeLayout ll = new RelativeLayout(this);
ll.setId(99);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("txt1");
tv.setId(1);
TextView tv2 = new TextView(this);
tv2.setText("txt2");
tv2.setId(2);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.ALIGN_PARENT_TOP);
ll.addView(tv, lay);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());
ll.addView(tv2, p); this.setContentView(sv);};
答案 0 :(得分:21)
p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());
此行表示tv2的底部与tv的底部对齐 - 换句话说,它们将相互覆盖。您想要的属性大概是RelativeLayout.BELOW
。但是,我强烈建议您使用xml。
答案 1 :(得分:5)
使用:
p.addRule(RelativeLayout.BELOW, tv.getId());
答案 2 :(得分:2)
你遗漏了各种各样的东西,首先ScrollView没有措施,用LayoutParams.FILL_PARENT或WRAP_CONTENT设置它,第二个; TextView1放错了所以TextView2,用lay.addRule设置TextView1位置(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
RelativeLayout ll = new RelativeLayout(this);
ll.setId(99);
sv.addView(ll, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
TextView tv = new TextView(this);
tv.setText("txt1");
tv.setId(1);
TextView tv2 = new TextView(this);
tv2.setText("txt2");
tv2.setId(2);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
ll.addView(tv, lay);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());
ll.addView(tv2, p);
this.setContentView(sv);};