以编程方式将项目添加到相对布局

我到处寻找这个问题的答案。 我是新来的Android,并试图通过java而不是xml编程添加项目到相对布局。 我已经创build了一个testing类来尝试,但项目保持堆叠,而不是格式正确。 我现在简单地想要一个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);}; 

Solutions Collecting From Web of "以编程方式将项目添加到相对布局"

  p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); 

这条线意味着电视2的底部与电视的底部alignment,换句话说,它们将互相覆盖。 你想要的财产大概是RelativeLayout.BELOW 。 不过,我强烈build议使用xml来代替。

使用:

 p.addRule(RelativeLayout.BELOW, tv.getId()); 

你错过了各种各样的事情,首先ScrollView没有措施,设置它与LayoutParams.FILL_PARENT或WRAP_CONTENT,第二; 它TextView1放错位置,所以TextView2,设置TextView1位置与lay.addRule(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);};