Android Override 9-patch padding in XML of one side
Asked Answered
S

1

6

When using a 9-patch image as a background, the padding seems to be always derived from the 9-patch image. Even if you do not use a padding bar in the 9 patch image it uses the drawable.

If the padding lines are not included, Android uses the left and top lines to define this drawable area.

http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

However you can override it in the XML by using android:padding=0dp or =Xdp. Unfortunately using android:paddingLeft=Xdp does not work. So you are stuck with uniform padding. I tried doing this:

  android:padding="2dp"
  android:paddingLeft="20dp"

It had no effect on the padding on the left. Placing them in a styles.xml produced similar results.

The only hack I have seen to get around this was to set the padding in code.

Segovia answered 30/12, 2012 at 22:8 Comment(0)
F
7

if (android:padding presented) it overrides all other padding values else if (android:paddingXXX presented) it overrides bg drawable paddingXXX (XXX = Left|Right|Top|Bottom) else if (view has drawable bg) padding values from this drawable (nine-patch in your case) will be used else default padding will be applied (zero usually)

So do no use android:padding="2dp". padding property overrides everything. Just use paddingLeft = 20dp, paddingTop = 2dp, paddingRight = 2dp, paddingBottom = 2dp.

Or you can set paddingLeft = 20dp and other padding values will be taken from bg drawable.

Flaw answered 30/12, 2012 at 23:13 Comment(2)
Thanks, I thought setting styles would work like CSS. This solved the problem. A lead on question but if I use view.setBackgroundResource(9patch_background); The 9patch_background overrides the padding set through XML is there a way to set background without overriding padding in XML.Segovia
you should get padding values, set background, set old padding values back.Flaw

© 2022 - 2024 — McMap. All rights reserved.