我有一个相对的布局,我正在以编程方式创建:
RelativeLayout layout = new RelativeLayout( this );
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
现在我有两个按钮,我想添加到这个相对布局。但问题是两个按钮都显示在relativelayout的左边,彼此重叠。
buttonContainer.addView(btn1);
buttonContainer.addView(btn2);
现在我想知道如何以编程方式设置android:layout_alignParentRight="true"
或android:layout_toLeftOf="@id/btn"属性的按钮,因为我们在xml?
芬兰湾的科特林版:
将这些扩展与中缀函数一起使用,可以简化以后的调用
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
infix fun View.leftOf(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}
infix fun View.alightParentRightIs(aligned: Boolean) {
val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
if (aligned) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
} else {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
}
this.layoutParams = layoutParams
}
然后将它们用作中缀函数调用:
view1 below view2
view1 leftOf view2
view1 alightParentRightIs true
或者你也可以将它们作为普通函数使用:
view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)