以编程方式将项目添加到一个相对布局 [英] Programmatically adding items to a relative layout

查看:149
本文介绍了以编程方式将项目添加到一个相对布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在到处寻找一个答案。我是新来的Andr​​oid,并试图以编程方式通过Java而不是XML为项目添加到一个相对布局。我创建了一个测试类尝试一下,但项目一直堆放正确的格式,而不是。我只是希望对方在一个TextView的,现在(最终我将使用的参数的左侧和右侧,但我开始很简单。我缺少什么?

 公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    滚动型SV =新的滚动型(本);
    RelativeLayout的LL =新的RelativeLayout(本);
    ll.setId(99);
    sv.addView(Ⅱ);
    TextView的电视=新的TextView(本);
    tv.setText(TXT1);
    tv.setId(1);
    TextView中TV2 =新的TextView(本);
    tv2.setText(TXT2);
    tv2.setId(2);
    RelativeLayout.LayoutParams奠定=新RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    lay.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    ll.addView(电视打好);
    RelativeLayout.LayoutParams P =新RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    p.addRule(RelativeLayout.ALIGN_BOTTOM,tv.getId());
    ll.addView(TV2,p)的; this.setContentView(SV);};


解决方案

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

此线意味着TV2的底部与电视的换句话说底部对齐,它们将互相覆盖起来。你想要的属性是presumably RelativeLayout.BELOW 。然而,我强烈建议使用XML这个代替。

I have been searching everywhere for an answer to this question. I'm new to Android and attempting to add items to a relative layout programmatically through java instead of xml. I have created a test class to try it out but the items keep stacking instead of formatting correctly. I simply want one TextView under the other for now (eventually I will use the left of and right of parameters but I am starting simple. What am I missing?

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

解决方案

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

This line means that the the bottom of tv2 is aligned with the bottom of tv- in other words, they will cover each other up. The property you want is presumably RelativeLayout.BELOW . However, I strongly recommend using xml for this instead.

这篇关于以编程方式将项目添加到一个相对布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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