在这个、这个和这个线程中,我试图找到有关如何在单个视图上设置边距的答案。但是,我想知道是否有更简单的方法。我将解释为什么我不想使用这种方法:
我有一个扩展按钮的自定义按钮。如果背景设置为默认背景以外的其他设置(通过调用 或setBackgroundResource(int id)
)setBackgroundDrawable(Drawable d)
,我希望边距为 0。如果我这样调用:
public void setBackgroundToDefault() { backgroundIsDefault = true; super.setBackgroundResource(android.R.drawable.btn_default); // Set margins somehow }
我希望边距重置为 -3dp(我已经在这里阅读了如何从像素转换为 dp,所以一旦我知道如何以像素为单位设置边距,我就可以自己管理转换)。但是因为这是在CustomButton
类中调用的,父级可以从 LinearLayout 到 TableLayout 不等,我宁愿不让他得到他的父级并检查那个父级的实例。我想这也将是相当低效的。
另外,在调用(使用 LayoutParams)时parentLayout.addView(myCustomButton, newParams)
,我不知道这是否会将它添加到正确的位置(但是还没有尝试过),比如五行中的中间按钮。
问题:除了使用 LayoutParams 之外,是否有更简单的方法以编程方式设置单个 Button 的边距 ?
编辑:我知道 LayoutParams 方式,但我想要一个避免处理每种不同容器类型的解决方案:
ViewGroup.LayoutParams p = this.getLayoutParams(); if (p instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)p; if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb); else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb); this.setLayoutParams(lp); } else if (p instanceof RelativeLayout.LayoutParams) { RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)p; if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb); else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb); this.setLayoutParams(lp); } else if (p instanceof TableRow.LayoutParams) { TableRow.LayoutParams lp = (TableRow.LayoutParams)p; if (_default) lp.setMargins(mc.oml, mc.omt, mc.omr, mc.omb); else lp.setMargins(mc.ml, mc.mt, mc.mr, mc.mb); this.setLayoutParams(lp); } }
因为this.getLayoutParams();
返回的 aViewGroup.LayoutParams
没有属性topMargin
, bottomMargin
, leftMargin
, rightMargin
。您看到的 mc 实例只是一个MarginContainer
包含偏移 (-3dp) 边距和 (oml、omr、omt、omb) 和原始边距 (ml、mr、mt、mb) 的 a。