如何在xml中的代码中设置RelativeLayout布局参数(How to set RelativeLayout layout params in code not in xml?)

编程入门 行业动态 更新时间:2024-10-20 16:48:39
如何在xml中的代码中设置RelativeLayout布局参数(How to set RelativeLayout layout params in code not in xml?)

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

如何在代码中设置布局,而不是XML?

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

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);

你可以看到,这是你必须做的:

创建一个RelativeLayout.LayoutParams对象。 使用addRule(int)或addRule(int, int)设置规则。 第一种方法用于添加不需要值的规则。 将参数设置为视图(在本例中为每个按钮)。

Just a basic example:

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:

Create a RelativeLayout.LayoutParams object. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values. Set the parameters to the view (in this case, to each button).

更多推荐

本文发布于:2023-08-07 03:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1460766.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布局   参数   代码   如何在   params

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!