2

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?

lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • @pskink thanks. I don't fully understand how creating a BitmapDrawable fixes my problem, could you further explain? IE how would I go about creating a bitmapdrawable that "fills" the buttons leftDrawable space? – lostintranslation Apr 15 '18 at 14:15
  • No, I want to create my own "image" in a button drawables area. IE a button has a leftDrawable, rightDrawable, etc. I am trying to do it programmatically. So doing this programmatically I am trying to start simple by drawing 2 colored boxes above. Just to figure out how it works. – lostintranslation Apr 15 '18 at 14:24

2 Answers2

0

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

0

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.

rahul.taicho
  • 1,339
  • 1
  • 8
  • 18