Android以编程方式设置底部边距

时间:2017-09-29 03:11:27

标签: android layout

是否可以使用RelativeLayout.LayoutParams指定对象的下边距?我想仅指定底部边距。

2 个答案:

答案 0 :(得分:2)

尝试这样。

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

注意

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

答案 1 :(得分:0)

是可能的,但它可能表明您想要做的事情可以以更合适的方式完成。那么,这个要求背后的原因是什么?

如果您确实需要以编程方式而不是通过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);

要注意两个细节:边距以像素为单位,但xml布局以dps为单位;此外,对于每种视图类型,您都需要转换为自己特定的布局参数类型。