How to create simple layer drawable in button

216 Views Asked by At

I am trying to better understand how layer drawables work within a buttons drawable(s).

I am trying to draw 2 simple colored boxes, one without insets so that it fills the entire button drawable area. And one with some inset.

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);

However that doesn't work at all. The first problem is that the boxes are not filling any area. Is that because a buttons drawables(s) don't have a predefined size? If that is the case I tried to set the bound manually on the boxes, but didn't have much luck either.

Can anyone help me understand what I am doing wrong?

2

There are 2 best solutions below

1
AudioBubble On

Create a Specific Design in Drawable and call in background button in xml

0
rahul.taicho On

The problem right now with ColorDrawable is that getIntrinsicWidth()/getIntrinsicHeight() that determine the bounds of the drawable are by default -1, thus it doesn't render on the screen. What would help in your case is to extend ColorDrawable and override the height and width from the constructor.

Here's a sample:

  class CustomDrawable(color: Int, val h: Int, val w: Int): ColorDrawable(color) {
    override fun getIntrinsicHeight(): Int {
      return h
    }

    override fun getIntrinsicWidth(): Int {
      return w
    }
  }

and then you can instantiate this instead of ColorDrawable like so

val background1 = CustomDrawable(Color.BLUE, dimensionInPx , dimensionInPx)
val background2 = CustomDrawable(Color.GREEN, dimensionInPx, dimensionInPx)

be sure to convert dp to px before passing these values

Hope this helps.