Tuesday, June 5, 2012

Laying out Views in RelativeLayout programmatically


I'm trying to achive the following programmatically (rather than declaratively via XML):




<RelativeLayout...>
<TextView ...
android:id="@+id/label1" />
<TextView ...
android:id="@+id/label2"
android:layout_below: "@id/label1" />
</RelativeLayout>



In other words, how do I make the second TextView appear below the first one, but I want to do it in code:




RelativeLayout layout = new RelativeLayout(this);
TextView label1 = new TextView(this);
TextView label2 = new TextView(this);
...
layout.addView(label1);
layout.addView(label2);
setContentView(layout);



Update:



Thanks, TreeUK. I understand the general direction, but it still doesn't work - "B" overlaps "A". What am I doing wrong?




RelativeLayout layout = new RelativeLayout(this);
TextView tv1 = new TextView(this);
tv1.setText("A");

TextView tv2 = new TextView(this);
tv2.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

layout.addView(tv1);
layout.addView(tv2, lp);


Source: Tips4all

2 comments:

  1. From what I've been able to piece together, you have to add the view using LayoutParams.

    LinearLayout linearLayout = new LinearLayout(this);

    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.addRule(RelativeLayout.ALIGN_WITH_PARENT_TOP);

    parentView.addView(linearLayout, relativeParams);


    All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

    TextView tv1 = new TextView(this);
    tv1.setId(1);
    TextView tv2 = new TextView(this);
    tv2.setId(2);


    Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

    ReplyDelete
  2. Just spent 4 hours with this problem. Finally realized that you must not use zero as view id. You would think that it is allowed as NO_ID == -1, but things tend to go haywire if you give it to your view...

    ReplyDelete