如何以编程方式设置

如何以编程方式设置

本文介绍了如何以编程方式设置相对布局中按钮的 layout_align_parent_right 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a relative layout which I am creating programmatically:

 RelativeLayout layout = new RelativeLayout( this );
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);

现在我想在这个相对布局中添加两个按钮.但问题是两个按钮都显示在 RelativeLayout 的左侧,彼此重叠.

Now I have two buttons which I want to add in this relative layout. But the problem is both buttons are being shown on the left of the RelatiiveLayout overlapping on each other.

buttonContainer.addView(btn1);
buttonContainer.addView(btn2);

现在我想知道如何以编程方式设置 android:layout_alignParentRight="true"或 android:layout_toLeftOf="@id/btn" 按钮的属性,就像我们在 xml 中所做的那样?

Now I want to know how can I programmatically set the the android:layout_alignParentRight="true"or android:layout_toLeftOf="@id/btn" attribute of buttons as we do in the xml?

推荐答案

您可以使用 View.getLayoutParams 从代码中访问任何 LayoutParams.您只需要非常清楚您访问的是什么 LayoutParams.这通常是通过检查包含的 ViewGroup 来实现的,如果它有一个 LayoutParams 内部孩子,那么你应该使用它.在您的情况下,它是 RelativeLayout.LayoutParams.您将使用 RelativeLayout.LayoutParams#addRule(int 动词)RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

您可以通过代码获取:

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

这篇关于如何以编程方式设置相对布局中按钮的 layout_align_parent_right 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:44