简体   繁体   English

Android以编程方式设置底边距

[英]Android set bottom margin programmatically

Is it possible to use RelativeLayout.LayoutParams to specify a bottom margin for an object? 是否可以使用RelativeLayout.LayoutParams指定对象的底部边距? I would like to specify the bottom margin only. 我只想指定底部边距。

try like this . 这样尝试。

TextView mTvLine = findViewById(R.id.tv_line);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// add rule
params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.ll_status);
params.setMargins(0, 0, 0, 0);
mTvLine.setLayoutParams(params);

NOTE 注意

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

// Child widget relative to the widget: imageViewId is ABOVE of it
relativeLayoutParams.addRule(RelativeLayout.ABOVE, imageViewId.getId());

// Child widget relative to the widget: imageViewId is BELOW of it
relativeLayoutParams.addRule(RelativeLayout.BELOW, imageViewId.getId());

//  Child widget relative to the widget: aligned with the bottom of the imageViewId
relativeLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, imageViewId.getId());

// The following three methods represent the same, indicating that the child widget is at the bottom of the parent widget
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);//
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);  

Yes is possible, but it could be an indication that what you want to do could be done in a more appropriate way. 是可以的,但这可能表明您可以以更适当的方式完成您想做的事情。 So, what's the reasoning behind this request? 那么,此请求背后的原因是什么?

In case you really need to do it programmatically instead of via xml layout, you can do it like this: 如果您确实需要以编程方式而不是通过xml布局来执行此操作,则可以执行以下操作:

View myView = findViewById(R.layout.my_view);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
params.bottomMargin = 23;  // your new value, in pixels
view.setLayoutParams(params);

Two details to be careful: margins are in pixels, but xml layouts are in dps; 需要注意的两个细节:边距以像素为单位,而xml布局以dps为单位; also, for each view type you'll need to cast to its own specific layout parameters type. 此外,对于每种视图类型,您都需要转换为自己的特定布局参数类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM