Android - 9patch padding on a Button

坚强是说给别人听的谎言 提交于 2019-12-24 16:25:45

问题


I created a button with a 9patch image as a background. In the 9patch image I used the bottom and right lines to specify the content area/padding, to position the text on the button. This works well on a TextView, but on a Button the content lines seem to have no effect on the text position. Setting "paddingTop"/"paddingBottom" also seem to have no effect - only "padding" has any effect.

This is my layout XML:

<Button 
            android:layout_width="450dp"
            android:layout_height="198dp"
            android:text="Some text here"
            android:gravity="center"
            android:background="@drawable/my_button"/>

Is there any way to set the padding? Maybe I could use a different View instead of a Button? For example, I could try to just use a TextView and make it clickable, but I'm not sure what other side-effects this will have.


回答1:


Explicitly setting android:padding="@null" solved my issue.

The issue seemed to be that a Button (or one of the styles in the theme I'm using) is setting the padding, which overrides all other padding in the button - padding in the background drawable, as well as paddingTop, paddingLeft etc.

My button layout is now defined like this:

<Button 
        android:layout_width="450dp"
        android:layout_height="198dp"
        android:text="Some text here"
        android:gravity="center"
        android:padding="@null"
        android:background="@drawable/my_button"/>

My IDE (IntelliJ IDEA 11.1) picked up the @null as an error, even though it compiled. Setting it to -1px also worked.




回答2:


If you use a 9-patch image as background, both the padding and the stretched areas are defined in the background.

It's quite graphic if you use the draw9patch tool: the padding is defined (indirectly) with the content area (lines on right and bottom): http://developer.android.com/guide/developing/tools/draw9patch.html



来源:https://stackoverflow.com/questions/10009343/android-9patch-padding-on-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!