在java中code设置RelativeLayout的 [英] Setting up RelativeLayout in java code

查看:148
本文介绍了在java中code设置RelativeLayout的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难得到两个文本的观点出现在彼此的顶部在我的Java code。这里的code我尝试用:

I'm having a hard time getting two text views to appear on top of each other in my java code. Here's the code I'm experimenting with:

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        layout = new RelativeLayout(this);
        text1 = new TextView(this);
        text1.setText("1");
        text2 = new TextView(this);
        text2.setText("2");

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams q = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        q.addRule(RelativeLayout.BELOW, layout.getId());
        text1.setLayoutParams(q);
        layout.addView(text1);


        p.addRule(RelativeLayout.BELOW,text1.getId());
        text2.setLayoutParams(p);
        layout.addView(text2);

        setContentView(layout);
    }

这堆在同一行的两个文本的意见,但我想的TextView文本2,出现以下TextView的文本1,所以在我的应用程序我想下面的显示为输出:

This stacks the two text views on the same line, but I want TextView text2, to appear below TextView text1, so in my app I want the following to appear as the output:

1
2

我已经尝试了所有种类的事情了addRule的方法,我不知道为什么,这是行不通的。我想知道如何,因为我计划建立的方法库,可以建立一个布局,很容易调整通过编辑阵列做没有XML。

I've tried all sort of things with the "addRule" method, I'm not sure why this isn't working. I want to know how to do this without XML because I plan to build a library of methods that can build up a layout that is easily adjustable through editing an array.

推荐答案

TextViews 没有一个ID(默认情况下,id为 -1 )......它们的初始化之后把这样的:

Your TextViews don't have an id (by default the id is -1)... put this after their initialization:

text1.setId(1111); // 1111 is just an example,
text2.setId(2222); // just make sure the id are unique

这篇关于在java中code设置RelativeLayout的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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