Search code examples
androidpaddingnine-patch

Android Override 9-patch padding in XML of one side


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.


Solution

  • 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.