suhas_sm
suhas_sm

Reputation: 2114

Unable to align text after adding 9-patch as button background

I have a button on which text need to be aligned at center horizontally. Gravity works fine when the button is without the 9 Patch as a background. But as soon I add a 9 patch as a back ground the gravity shifts towards left and text refuses to budge no matter what gravity is set to.

I have tried setting padding to 0dip, -1px, @null as suggested on some other threads. None of them worked. I am changing background from within the code also using setBackgroundResource() as my requirements are pinned to API level 8, so other methods to set background is not an option. Also I can't use selector list to do this because I need that button to be in selected state (Like a toggle button).

Any inputs ?

Upvotes: 1

Views: 2644

Answers (5)

Jcy
Jcy

Reputation: 66

Check and assign 9-patch image content area for EVERY state of that button's background.

I once forgot to set 9-patch image content area for pressed state of button, which somehow lead to wired padding behavior in normal state.

Upvotes: 0

shmulik.r
shmulik.r

Reputation: 1111

Adding android:padding="0dp" to the Button worked for me.

Upvotes: 1

tomash
tomash

Reputation: 12962

Here is another approach to this problem: Center horizontaly and/or verticaly with 9 patch in Android

It uses RelativeLayout with 9-patch background and TextView put inside. You can then format and align text as you like without breaking 9-patch marigins and padding.

Upvotes: 1

suhas_sm
suhas_sm

Reputation: 2114

I had to set padding to 0 after each time I set background, programmatically ! That solved my problem.

Thanks

Upvotes: 5

It is because in your 9-patch image you have assigned content area(see right bottom part).

Generally Right and Bottom part are for content padding (optional) so if you want to set padding via programming then don't manipulate Bottom and Right area of 9 patch.

enter image description here

Upvotes: 7

Related Questions