我有一个自定义按钮,它扩展了按钮。如果将背景设置为默认背景之外的其他内容(通过调用
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,所以一旦我知道如何设置像素边距,就可以自己进行转换)。但由于这是在
CustomButton
类中调用的,父项可以从LinearLayout变为TableLayout,我不想让他获取其父项并检查该parent的instanceof。我想象那也会相当低效。
此外,在调用(使用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)的边距,以及原始边距(ml, mr, mt, mb)。