Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button with text AND an image (Android)

I want to create an android button with both an image and text, but the text is automatically centered. How do I place the text at the bottom of the button?

I know I can use relative layout to place a second text button underneath the image, but I prefer to minimize the code.

like image 357
SnowboardBruin Avatar asked Jul 22 '11 16:07

SnowboardBruin


2 Answers

You can also do like this

enter image description here

<LinearLayout
android:id="@+id/image_button_2"
style="@android:style/Widget.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dp"
    android:src="@drawable/ic_gear" />

<TextView
    android:id="@+id/image_button_2_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:text="Button 2" />

    </LinearLayout>

In your activity

 final View button2 = findViewById(R.id.image_button_2);
 button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
like image 147
Trupti Avatar answered Oct 20 '22 10:10

Trupti


You can declare where on the button you want to assign the image (Im assuming you already have the image on the button):

<Button
   android:id="@+id/button"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="- I'm a Button -"
   android:drawableTop="@drawable/icon"
   />

you can also set padding between the text and image with android:drawablePadding(int)

The drawableTop attribute can be changed to drawableRight, Left, Bottom, etc. good luck!

like image 36
Adam Storm Avatar answered Oct 20 '22 09:10

Adam Storm