Can I Set "android:layout_below" at Runtime Programmatically?

AlanH picture AlanH · Jul 18, 2010 · Viewed 102.9k times · Source

Is it possible when creating a RelativeLayout at runtime to set the equivalent of android:layout_below programmatically?

Answer

Rich Schuler picture Rich Schuler · Jul 18, 2010

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.