【发布时间】:2019-03-17 13:58:14
【问题描述】:
我一直在尝试为以编程方式创建的 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);
但我得到“无法解决符号参数”
如何为以编程方式创建的视图设置边距?
【问题讨论】:
-
你初始化参数了吗? LinearLayout.LayoutParams 参数 =...
标签: android margins programmatically-created