Android:如何以编程方式设置 LinearLayout 边距
Posted
技术标签:
【中文标题】Android:如何以编程方式设置 LinearLayout 边距【英文标题】:Android: How to set LinearLayout marging programmatically 【发布时间】: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 参数 =... 【参考方案1】:试试这个:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);
【讨论】:
以上是关于Android:如何以编程方式设置 LinearLayout 边距的主要内容,如果未能解决你的问题,请参考以下文章
如何在android中以编程方式设置ImageView的高度宽度?