android - Android:如何以编程方式设置 LinearLayout 边距
问题描述
我一直在尝试为以编程方式创建的 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();
}
}
但它没有用,所以我从另一个答案here尝试了这个
parameter = (LinearLayout.LayoutParams) linearLayout.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
linearLayout.setLayoutParams(parameter);
但我得到“无法解决符号参数”
如何为以编程方式创建的视图设置边距?
解决方案
尝试这个:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);
推荐阅读
- toggle - Mapbox:当一个可见时,所有图层都不可见
- c# - 产品部署后,Hangfire 自动启动所有重复作业
- php - 从 php 中的 mysql 表中选择计数(列)
- reactjs - React npm 包:我需要不同的 webpack 配置来保证 ssr 安全吗?
- json - (Shopify) 如何使用当前主题 JSON + AJAX 设置更新关于变体更改的库存消息
- .net - 在 .NET 对象上设置 Enum 属性
- python - 选择查询:错误代码 1292 - 截断不正确的 DOUBLE 值
- php - 按过期日期对结果进行排序,最后过期
- python - 由 emojize 生成的表情符号不会显示在电子邮件中
- javascript - 主机“xxxx”、用户“没有 pg_hba.conf 条目
“,数据库” ", SSL 关闭