问题
Is it possible when creating a RelativeLayout at runtime to set the equivalent of android:layout_below
programmatically?
回答1:
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.
回答2:
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);
回答3:
While @jackofallcode answer is correct, it can be written in one line:
((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
来源:https://stackoverflow.com/questions/3277196/can-i-set-androidlayout-below-at-runtime-programmatically