views:

7756

answers:

2

I'm trying to have an image (as the background) on a button and add dynamically, depending on what's happening during run-time, some text above/over the image.

If I use ImageButton I don't even have the possibility to add text. If I use Button I can add text but only define an image with android:drawableBottom and similar XML attributes as defined here.

However these attributes only combine text & image in x- and y-dimensions, meaning I can draw an image around my text, but not below/under my text (with the z-axis defined as coming out of the display).

Any suggestions on how to do this? One idea would be to either extend Button or ImageButton and override the draw()-method. But with my current level of knowledge I don't really know how to do this (2D rendering). Maybe someone with more experience knows a solution or at least some pointers to start?

Thanks

+5  A: 

You can use setBackgroundDrawable() on Button to set the background of a button.

Any text will appear above the background.

If you are looking for something similar in xml there is: android:background attribute which does the same

Vitaly Polonetsky
If you go this route, you do not want to just use a simple drawable for the background. Use a StateListDrawable (usually via <selector> XML file in res/drawable/), so you can define backgrounds for the various states (normal, pressed, focused, disabled, etc.).
CommonsWare
Agree with you, look for this question and my answer:http://stackoverflow.com/questions/1533038/android-specify-two-different-images-for-togglebutton-using-xml
Vitaly Polonetsky
How stupid. How could I have missed that in the documentation. Thanks for the quick answer and also the hint with the <selector>. That's something I definitely want to implement in the future.
znq
+5  A: 

For users who just want to put Background, Icon-Image and Text in one Button from different files: Use background, drawableTop/Bottom/Rigth/Left and padding Attributes.

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/home_btn_test"
        android:drawableTop="@drawable/home_icon_test"
        android:textColor="#FFFFFF"
        android:id="@+id/ButtonTest"
        android:paddingTop="32sp"
        android:drawablePadding="-15sp"
        android:text="this is text"></Button>
OneWorld