【发布时间】:2012-09-25 13:08:28
【问题描述】:
在this、this 和this 线程中,我试图找到有关如何在单个视图上设置边距的答案。但是,我想知道是否没有更简单的方法。我将解释为什么我不想使用这种方法:
我有一个扩展 Button 的自定义 Button。如果背景设置为默认背景以外的其他内容(通过调用setBackgroundResource(int id) 或setBackgroundDrawable(Drawable d)),我希望边距为0。如果我这样称呼:
public void setBackgroundToDefault() {
backgroundIsDefault = true;
super.setBackgroundResource(android.R.drawable.btn_default);
// Set margins somehow
}
我希望将边距重置为 -3dp(我已经阅读了 here 如何从像素转换为 dp,所以一旦我知道如何以 px 为单位设置边距,我就可以自己管理转换)。但由于这是在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();返回一个ViewGroup.LayoutParams,它没有topMargin、bottomMargin、leftMargin、rightMargin的属性。
您看到的 mc 实例只是一个 MarginContainer,其中包含偏移 (-3dp) 边距和 (oml, omr, omt, omb) 和原始边距 (ml, mr, mt, mb)。
【问题讨论】: