RelativeLayout有方法addRule可以动态设置alignParent、margin、控件相对位置的设置,比如需要设置childView右边距离RelativeLayout右边距为20dp:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View childView = findViewById(R.id.child1);
RelativeLayout parent = findViewById(R.id.parent);
RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) childView.getLayoutParams();
lps.rightMargin = dip2px(this, 20.0f);
lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
最终效果图: