在this、this和this线程中,我试图找到如何在单个视图上设置边距的答案.不过,我想知道有没有更简单的方法.我将解释为什么我不想使用这种方法:
我有一个自定义按钮,它扩展了按钮.如果背景设置为默认背景以外的内容(通过调用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)
时,我不知道这是否会将其添加到正确的位置(但尚未try ),比如说五行的中间按钮.
问题:有没有更简单的方法来编程设置单个按钮的边距
编辑:我知道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
.