Buttons text is not aligned any more after changing the BackgroundDrawable

349 Views Asked by At

i am changing my buttons' backgroundDrawable programaticaly:

myButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_button_blue));

After changing the background, the text in the button is not aligned any more like it was before changing the background.

buttons before and after changing its background
(source: dsliga.eu)

target SDK version is 10. Thanks.

2

There are 2 best solutions below

1
On BEST ANSWER

Looks like the setText() method messes up the alignment. After changing the text, re-applying the gravity and padding did the job:

myButton.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
myButton.setPadding(12, 12, 12, 12);
1
On

Since you are using a 9patch, you need to specify with bottom and right side lines where the data is inside your drawing, you probably did not draw a full line at the bottom, and right side of the 9patch drawing

this is why the text inside your button stopped being centered, because the bounds of the 9patch are NOT what you think they are

your 9patch should (normally), leave only 1 pixel at the top and bottom of the right side line, and 1 pixel at the left and right of the bottom line

redraw the 9patch, remove the gravity and padding code, and see if it works

see below image

enter image description here