How to lay out Views in RelativeLayout programmatically? How to lay out Views in RelativeLayout programmatically? android android

How to lay out Views in RelativeLayout programmatically?


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.MATCH_PARENT, LayoutParams.MATCH_PARENT);relativeParams.addRule(RelativeLayout.ALIGN_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());


Cut the long story short:With relative layout you position elements inside the layout.

  1. create a new RelativeLayout.LayoutParams

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(...)

    (whatever... fill parent or wrap content, absolute numbers if you must, or reference to an XML resource)

  2. Add rules:Rules refer to the parent or to other "brothers" in the hierarchy.

    lp.addRule(RelativeLayout.BELOW, someOtherView.getId())lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
  3. Just apply the layout params: The most 'healthy' way to do that is:

    parentLayout.addView(myView, lp)

Watch out: Don't change layout from the layout callbacks. It is tempting to do so because this is when views get their actual sizes. However, in that case, unexpected results are expected.


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...