AlanH
AlanH

Reputation: 2201

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

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

Upvotes: 218

Views: 113036

Answers (4)

Mahmoud
Mahmoud

Reputation: 2883

Kotlin version with infix function

infix fun View.below(view: View) {
      (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

Then you can write:

view1 below view2

Or you can call it as a normal function:

view1.below(view2)

Upvotes: 5

CoolMind
CoolMind

Reputation: 28793

While @jackofallcode answer is correct, it can be written in one line:

((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);

Upvotes: 13

Rich Schuler
Rich Schuler

Reputation: 41972

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.

Upvotes: 483

jackofallcode
jackofallcode

Reputation: 1996

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

Upvotes: 154

Related Questions