如何以编程方式在相对布局中设置 TextViews 的 align parent right 属性

How to set the align parent right attribute of TextViews in relative layout programmatically

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

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

现在我有两个 TextView,我想将它们添加到这个相对布局中。但问题是两个 TextView 都显示在 RelativeLayout 的左侧,彼此重叠。

textViewContainer.addView(textView1);
textViewContainer.addView(textView2);

现在我想知道如何以编程方式设置

`android:layout_alignParentRight="true"`

`android:layout_toLeftOf="@id/textView"` 

我们在 xml?

中所做的 TextView 属性

使用方法addrule

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

您可以使用 View.getLayoutParams 从代码中访问任何布局参数。您只需要非常了解您访问的 LayoutParams。这通常是通过检查包含的 ViewGroup 来实现的,如果它有一个 LayoutParams 内部子项,那么这就是您应该使用的那个。在你的例子中是 RelativeLayout.LayoutParams。你会用 RelativeLayout.LayoutParams#addRule(int verb)RelativeLayout.LayoutParams#addRule(int verb, int anchor)

您可以通过代码获取:

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

textView.setLayoutParams(params); //causes layout updat

您需要将 LayoutParams 与每个视图对齐:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

然后为每个视图添加适当的规则:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 

第一个和

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);

到第二个。

然后将其应用于视图:

view.setLayoutParam(params)