2

I'm trying to create a CustomButton dynamically for java code with 10dp padding and 10dp rounded corners. I wrote the following:

public class CustomButton extends Button {

    private GradientDrawable gd;
    private ShapeDrawable sd;
    private LayerDrawable ld;
    private StateListDrawable sld;

    public CustomButton(Context context) {

        super(context);

        gd = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{Color.parseColor("#39D100"), Color.parseColor("#369212")});
        gd.setCornerRadius(10);

        sd = new PaintDrawable();
        sd.setPadding(10, 10, 10, 10);

        ld = new LayerDrawable( new Drawable[]{sd, gd} );

        sld = new StateListDrawable();
        sld.addState(new int[]{0,1}, ld);

        setBackgroundDrawable(sld);

    }

}

If I add only the GradientDrawable or only the ShapeDrawable to StateListDrawable it works correctly, but if I put both into the LayerDrawable the padding and corner parts will have a black background and not transparent as expected.

ScreenShot: image

user
  • 86,916
  • 18
  • 197
  • 190
Paldom
  • 21
  • 2

2 Answers2

1

To remove black background, clear the paint color with

sd.getPaint().setColor(0);
Ruslan Yanchyshyn
  • 2,774
  • 1
  • 24
  • 22
0

I think this can be achived with a custom selector for your button, rather than writing up a whole class. Take a look at this question: Standard Android Button with a different color

Community
  • 1
  • 1
Drejc
  • 14,196
  • 16
  • 71
  • 106