本文介绍了如何在不在 xml 中的代码中设置 RelativeLayout 布局参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我想在屏幕上添加 3 个按钮:一个左对齐,一个居中对齐,最后一个右对齐.

For example I want to add 3 buttons on screen: one align left, one align center, last one align right.

如何在代码中而不是在 xml 中设置它们的布局?

How can I set their layout in code, not in xml?

推荐答案

只是一个基本的例子:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

如您所见,这是您必须做的:

As you can see, this is what you have to do:

  1. 创建一个 RelativeLayout.LayoutParams 对象.
  2. 使用addRule(int)addRule(int, int) 来设置规则.第一种方法用于添加不需要值的规则.
  3. 为视图设置参数(在本例中为每个按钮).
  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

这篇关于如何在不在 xml 中的代码中设置 RelativeLayout 布局参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:05