0

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.

Community
  • 1
  • 1
Dusan
  • 3,284
  • 6
  • 25
  • 46

2 Answers2

1

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);
Dusan
  • 3,284
  • 6
  • 25
  • 46
  • Still not 100% satisfied. This solves the alignment of the text in the button, but the buttons get stretched. I have 12 buttons in a table layout, but after changing the BackgroundDrawable, the buttons in rows are not equally big. Some of them are shorter than the others. – Dusan Jan 14 '14 at 22:46
0

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

Lena Bru
  • 13,521
  • 11
  • 61
  • 126
  • Just added the 2 extra black lines (i had only lines at top and left side), but it didn't solve the problem. My text in the button doesn't get aligned correctly. I had to put back the gravity and padding code. – Dusan Jan 14 '14 at 22:02