如何在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).更多推荐
发布评论