Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up RelativeLayout in java 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);
    }

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

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.

like image 785
Andi Jay Avatar asked Mar 16 '11 14:03

Andi Jay


People also ask

Is RelativeLayout deprecated?

relativelayout is deprecated now.

What is RelativeLayout?

RelativeLayout is a view group that displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center).

How do I find the height and width of RelativeLayout in android programmatically?

private int width, height; RelativeLayout rlParent = (RelativeLayout) findViewById(R. id. rlParent); w = rlParent. getWidth(); h = rlParent.


1 Answers

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
like image 65
Cristian Avatar answered Sep 28 '22 06:09

Cristian