我一直在尝试为以编程方式创建的LinearLayout设置边距
LinearLayout linearLayout = new LinearLayout(this);
setMargins(linearLayout,20,20,20,20);
private 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();
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
// convert the DP into pixel
int l = (int)(left * scale + 0.5f);
int r = (int)(right * scale + 0.5f);
int t = (int)(top * scale + 0.5f);
int b = (int)(bottom * scale + 0.5f);
p.setMargins(l, t, r, b);
view.requestLayout();
}
}
但是它没有用,所以我从另一个答案这里尝试了
parameter = (LinearLayout.LayoutParams) linearLayout.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
linearLayout.setLayoutParams(parameter);
但是我收到“无法求解符号参数”
如何为以编程方式创建的视图设置边距?
答案 0 :(得分:0)
尝试一下:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);