I need to add an icon and some text to a button, in code (not xml), in my Android app.
The icon (a stock icon, "expander_open_holo_light.9.png") should be on the left and the text on the right.
I can't find any clue...
Take a look at setCompoundDrawableWithIntrinsicBounds(). You can find the info here:
Basically, that is the way to set the android:drawableLeft property of your button programatically.
If you aren't doing much with the button (like resizing, instantiating a few of them) i would just create a custom xml view with an imageview and textview side by side contained in a container.
If you are changing the picture and text often, create a custom ImageView or Button class.
E.G textbutton.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/base"
android:orientation="horizontal"
android:layout_width="200dp"
android:layout_height="100dp"
android:gravity="center"
android:background="#ff623466">
<ImageView android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:src="@drawable/icon"
android:gravity="center"
/>
<TextView android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="Hello!"
android:gravity="center"
/>
</LinearLayout>
Then post this line in main.xml or any other layout you want the button:
<include layout="@layout/textbutton" />