如何在Java中的LinearLayout中设置页边距



我试图使用ViewGroup使用setMargins方法,但我一直收到setMargins is not defined的错误。这是我的代码:

LinearLayout content = new LinearLayout(activity);
LayoutParams params = content.getLayoutParams();
params.setMargins(0, 0, 0, 40);
content.setLayoutParams(params);

您应该使用LayoutParams来设置按钮边距:

LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,      
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);

根据您使用的布局,您应该使用RelativeLayout.LayoutParams或LinearLayout.LayoutParams.

要将dp度量转换为像素,请尝试以下操作:

Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure, 
r.getDisplayMetrics()
);

使用此方法根据任何视图(LinearLayout、RelativeLayout等(设置页边距

以整数格式传递参数

public static void setMargins(View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(left, top, right, bottom);
view.requestLayout();
}
}

最新更新