2

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

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a great answer! If you need separate functionality for the image and text (like onClick()) my answer may be better.
1

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" />

Comments

1

Take a TextView and set ImageView as the background.After setting image, append text to it. Text will be moved to right. Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.