Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, how to add icon *and* text to a button, programmatically?

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

like image 357
MarcoS Avatar asked Feb 06 '26 15:02

MarcoS


2 Answers

Take a look at setCompoundDrawableWithIntrinsicBounds(). You can find the info here:

http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)

Basically, that is the way to set the android:drawableLeft property of your button programatically.

like image 189
hooked82 Avatar answered Feb 09 '26 07:02

hooked82


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" />
like image 26
Ian Avatar answered Feb 09 '26 07:02

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!