How to create RelativeLayout programmatically in android

Android RelativeLayout enables you to specify how child views are positioned relative to each other. The position of each view can be specified as relative to sibling elements or relative to the parent.

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 of center).

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

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);
TextView tv2 = new TextView(this);
Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

and  you have to add this way too

With relative layout you position elements inside the layout.

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)

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

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

parentLayout.addView(myView, lp)


Happy Coding !!!

No comments:

Post a Comment


Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace