我有一个相对的布局,我正在以编程方式创建:

 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?


对象的创建和id 需要引用的按钮: btn1.setId (1); 你可以使用params变量来 添加参数到你的布局,我 认为方法是addRule(),检查 拿出android Java文档来做这个 LayoutParams对象。

你可以使用View.getLayoutParams从代码中访问任何LayoutParams。你只需要非常注意你访问的LayoutParams。这通常是通过检查包含的ViewGroup来实现的,如果它有LayoutParams内部子元素,那么这就是你应该使用的。在你的例子中是relativelayout。layoutparams。你将使用RelativeLayout。LayoutParams#addRule(int verb)和RelativeLayout。LayoutParams#addRule(int动词,int锚点)

你可以通过代码获得它:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //causes layout update

要添加一个值为true或false的RelativeLayout属性,请使用0表示false和RelativeLayout。千真万确:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams()
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)

属性是否已经添加并不重要,您仍然使用addRule(动词,主题)来启用/禁用它。然而,在api 17之后,你可以使用removeRule(动词),它只是addRule(动词,0)的快捷方式。

芬兰湾的科特林版:

将这些扩展与中缀函数一起使用,可以简化以后的调用

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)

在芬兰湾的科特林:

val params = mBinding.tvTotalAmount.layoutParams as RelativeLayout。LayoutParams

params.addRule (RelativeLayout.ALIGN_PARENT_END)

bbinding . tvtotalamount . layoutparams =参数