Android: possible to use 9 patch to draw the button? (see image)
-
28-10-2019 - |
Question
If I want to use the image as button background, how can I do it? 9 patch? Or fixed image(ldip/mdip/hdip)?
Thanks!
edit:
thanks for the two replies, I know the tool draw9patch, but I don't know how to define the vertical area so it won't destroy the gradient? Thanks!
Solution
I believe that a 9-patch would be the more elegant solution. You can use the "draw9patch" tool from the "tools" folder in your Android SDK to do this. The official Android documentation gives a good overview on how to use this : http://developer.android.com/guide/developing/tools/draw9patch.html
OTHER TIPS
To create a custom button you need:
A
<selector>
(state list) drawable that references different drawables for default/pressed/focused/disabled/etc. states.Each state should have a nine-patch (
.9.png
) drawable in each density (ldpi/mdpi/hdpi/xhdpi). Note that the framework can scale up or down, so you don't need to provide nine-patches for each density, but for best-looking results, you should do so.
So, your custom button drawable uses the following folder structure:
res/
drawable/
mybtn.xml # <selector> (state list)
drawable-hdpi/
mybtn_default.9.png
mybtn_pressed.9.png
mybtn_focused.9.png
mybtn_disabled.9.png
drawable-mdpi/
mybtn_default.9.png
mybtn_pressed.9.png
mybtn_focused.9.png
mybtn_disabled.9.png
drawable-xhdpi/
...
It should definitely be 9-patch. You will have to carefully select stretchable areas to not break the gradients though. Use the tool to preview how it would look on a button.
I'm not sure if it'll look good, but as 9-patch actually allows you to set multiple stretchable areas, you could try to set multiple vertical areas of 1 pixel high, and have all those stretch (basically, have a stretchable line every 2 pixels). This won't look as good as if the gradient worked perfectly, but might be good enough if you don't stretch it too much.