Android RelativeLayout中控件动态定位

1,148 阅读1分钟

背景

RelativeLayout是一种常用的布局,在实际开发过程中,有时控件的位置不是在xml就可以确定的,或者需要动态的变化,这时就需要在代码中进行动态设置。

场景

一、相对于父容器

相对于父容器只需要使用RelativeLayout类单参数addRule方法:

public void addRule(int verb) {
}

只需要传入相对父布局的定位常量(必须是有效常量)即可,例如:

View testView = findViewById(R.id.test_view);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) testView.getLayoutParams();
// 控件与父容器end对齐
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_END);
// 控件与父容器bottom对齐
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
testView.setLayoutParams(layoutParams);

一、相对于其他控件

相对于其他控件则需要使用RelativeLayout类两参数addRule方法:

public void addRule(int verb, int subject) {
}

第一个参数传入相对其他控件的定位常量,第二个参数传的是基准控件的控件ID,例如

View testView = findViewById(R.id.test_view);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) testView.getLayoutParams();
// 控件与基准控件(R.id.anchor_view)Start对齐
layoutParams.addRule(RelativeLayout.ALIGN_START, R.id.anchor_view);
// 控件在基准控件(R.id.anchor_view)的下方
layoutParams.addRule(RelativeLayout.BELOW, R.id.anchor_view);
testView.setLayoutParams(layoutParams);