Java 以编程方式在 LinearLayout 中设置边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2481455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set margins in a LinearLayout programmatically
提问by Timmmm
I'm trying to use Java (not XML) to create a LinearLayout with buttons that fill the screen, and have margins. Here is code that works without margins:
我正在尝试使用 Java(而不是 XML)来创建一个带有填充屏幕和边距的按钮的 LinearLayout。这是没有边距的代码:
LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
for (int r = 0; r < 6; ++r) {
Button btn = new Button(this);
btn.setText("A");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
lp.weight = 1.0f; // This is critical. Doesn't work without it.
buttonsView.addView(btn, lp);
}
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(buttonsView, lp);
So that works fine, but how on earth do you give the buttons margins so there is space between them? I tried using LinearLayout.MarginLayoutParams
, but that has no weight
member so it's no good. And it doesn't work if you pass it lp
in its constructor either.
所以这很好用,但是你到底如何给按钮边距以便它们之间有空间?我尝试使用LinearLayout.MarginLayoutParams
,但它没有weight
成员,所以不好。如果你lp
在它的构造函数中传递它,它也不起作用。
Is this impossible? Because it sure looks it, and it wouldn't be the first Android layout task you can only do in XML.
这是不可能的吗?因为它看起来确实如此,而且它不会是您只能在 XML 中执行的第一个 Android 布局任务。
采纳答案by Mauro
Here is a little code to accomplish it:
这是一个小代码来完成它:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
回答by CommonsWare
So that works fine, but how on earth do you give the buttons margins so there is space between them?
所以这很好用,但是你到底如何给按钮边距以便它们之间有空间?
You call setMargins()
on the LinearLayout.LayoutParams
object.
你叫setMargins()
的上LinearLayout.LayoutParams
对象。
I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.
我尝试使用 LinearLayout.MarginLayoutParams,但它没有权重成员,所以不好。
LinearLayout.LayoutParams
is a subclass of LinearLayout.MarginLayoutParams
, as indicated in the documentation.
LinearLayout.LayoutParams
是 的子类LinearLayout.MarginLayoutParams
,如文档中所示。
Is this impossible?
这是不可能的吗?
No.
不。
it wouldn't be the first Android layout task you can only do in XML
它不会是您只能在 XML 中执行的第一个 Android 布局任务
You are welcome to supply proof of this claim.
欢迎您提供此声明的证据。
Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.
就我个人而言,我不知道任何只能通过 XML 而不能通过 SDK 中的 Java 方法完成的事情。事实上,根据定义,一切都必须通过 Java 实现(尽管不一定通过 SDK 可访问的方法),因为 XML 不是可执行代码。但是,如果您知道某些事情,请指出,因为这是 SDK 中的一个错误,应该有一天会得到修复。
回答by Adam
To add margins directly to items (some items allow direct editing of margins), you can do:
要直接向项目添加边距(某些项目允许直接编辑边距),您可以执行以下操作:
LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
((MarginLayoutParams) lp).topMargin = ...;
((MarginLayoutParams) lp).leftMargin = ...;
//... etc
}
else
Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );
...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.
...无需了解/编辑周围布局即可工作。请注意“instanceof”检查,以防您尝试针对不支持边距的内容运行此检查。
回答by Karan Bhalodiya
Try this
尝试这个
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
回答by Rupesh Yadav
Due to variation in device screen pixel densities its good to always use DIP
unit to set margin programmatically. Like below_
由于设备屏幕像素密度的变化,最好始终使用DIP
unit 以编程方式设置边距。喜欢下面_
//get resources
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
//get layout params...
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.setMargins(Math.round(pxLeftMargin), Math.round(pxTopMargin), Math.round(pxRightMargin), Math.round(pxBottomMargin));
//set margin...
yourLayoutTOsetMargin.setLayoutParams(params);
Hope this will help.
希望这会有所帮助。
回答by Janith
I have set up margins directly using below code
我直接使用下面的代码设置了边距
LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(3, 300, 3, 3);
layout.setLayoutParams(params);
Only thing here is to notice that LayoutParams
should be imported for following package android.widget.RelativeLayout.LayoutParams
, or else there will be an error.
这里唯一要注意的是LayoutParams
应该为以下包导入android.widget.RelativeLayout.LayoutParams
,否则会出错。
回答by Francis Shi
/*
* invalid margin
*/
private void invalidMarginBottom() {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
lp.setMargins(0, 0, 0, 0);
frameLayoutContent.setLayoutParams(lp);
}
you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)
你应该注意view的viewGroup的类型。在上面的代码中,例如,我想改变frameLayout的margin,而frameLayout的view group是一个RelativeLayout,所以你需要转换为(RelativeLayout.LayoutParams)
回答by Ginni
MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
回答by Stappo
Here a single line Solution:
这里有一行解决方案:
((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));
回答by Makvin
Try this:
尝试这个:
MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;