在这个,这个和这个线程我试图找到如何在单个视图上设置边距的答案.但是,我想知道是否有更简单的方法.我会解释为什么我宁愿不想使用这种方法:
我有一个自定义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(我已经在这里阅读如何从像素转换为dp,所以一旦我知道如何在px中设置边距,我就可以自己管理转换).但是因为这是在CustomButton类中调用的,所以父级可以从LinearLayout变为TableLayout,而我宁愿不让他得到他的父级并检查该父级的实例.我想,这也将是非常无形的.
另外,在调用时(使用LayoutParams)parentLayout.addView(myCustomButton, newParams),我不知道这是否将它添加到正确的位置(但是没有尝试过),比如一行五的中间按钮.
问题:除了使用LayoutParams之外,还有更简单的方法以编程方式设置单个按钮的边距吗?
编辑:我知道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).