Android 如何创建简单的图层可绘制按钮
我试图更好地理解图层可绘制是如何在按钮可绘制中工作的 我试图画2个简单的彩色框,一个没有插图,这样它就填满了整个按钮可绘制区域。还有一个有一些插图Android 如何创建简单的图层可绘制按钮,android,android-drawable,android-button,layerdrawable,Android,Android Drawable,Android Button,Layerdrawable,我试图更好地理解图层可绘制是如何在按钮可绘制中工作的 我试图画2个简单的彩色框,一个没有插图,这样它就填满了整个按钮可绘制区域。还有一个有一些插图 ColorDrawable background1 = new ColorDrawable(Color.BLUE); ColorDrawable background2 = new ColorDrawable(Color.GREEN); Drawable[] drawables = new Drawable[] { background1,
ColorDrawable background1 = new ColorDrawable(Color.BLUE);
ColorDrawable background2 = new ColorDrawable(Color.GREEN);
Drawable[] drawables = new Drawable[] {
background1,
background2
};
LayerDrawable ld = new LayerDrawable(drawables);
ld.setLayerInset(0, 0, 0, 0, 0 ); // no inset on white box
ld.setLayerInset(1, 8, 8, 8, 8 ); // 8 inset on all side on green box
// set the left drawable on the button
button.setCompoundDrawablesWithIntrinsicBounds(ld, null, null, null);
然而,这根本不起作用。第一个问题是盒子没有填满任何区域。这是不是因为按钮可抽件没有预定义的尺寸?如果是这样的话,我试图在盒子上手动设置边界,但也没有太多运气
有人能帮我理解我做错了什么吗?在Drawable中创建一个特定的设计,并在xml中调用后台按钮ColorDrawable目前的问题是,
getIntrinsicWidth()/getIntrinsicHeight()
确定Drawable边界的默认值为-1,因此,它不会在屏幕上渲染。在您的情况下,可以帮助您扩展ColorDrawable
,并覆盖构造函数中的高度和宽度
以下是一个示例:
class CustomDrawable(color: Int, val h: Int, val w: Int): ColorDrawable(color) {
override fun getIntrinsicHeight(): Int {
return h
}
override fun getIntrinsicWidth(): Int {
return w
}
}
然后你可以实例化它,而不是像这样的ColorDrawable
val background1 = CustomDrawable(Color.BLUE, dimensionInPx , dimensionInPx)
val background2 = CustomDrawable(Color.GREEN, dimensionInPx, dimensionInPx)
在传递这些值之前,请确保将dp转换为px
希望这有帮助 @pskink谢谢。我不完全明白创建位图绘图是如何解决我的问题的,你能进一步解释一下吗?IE如何创建一个“填充”按钮左侧可绘制空间的bitmapdrawable?不,我想在按钮可绘制区域创建我自己的“图像”。IE一个按钮有一个leftDrawable,rightDrawable,等等。我试图用编程的方式来实现它。因此,以编程的方式来做这件事,我试图从上面画两个彩色框开始。只是想弄清楚它是如何工作的。我想用程序来做这件事。