Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a drawable in a Button with background and no text

Tags:

android

button

I have a few buttons in my Android app. They each look kinda like this:

<Button
    android:id="@+id/button_1"
    android:drawableTop="@drawable/an_icon"
    android:background="@drawable/a_background"
    android:layout_width="size_dp"
    android:layout_height="size_dp">
</Button>

Granted, I'm new to Android dev, but I can't figure out how to center the drawable in my button. I've tried the different drawableLocations, margins and padding for the button and its container, as well as drawablePadding, but I can't seem to get it done. Is there a way to center the drawable without abandoning Button for another View?

like image 225
HarryHippo Avatar asked Feb 11 '14 19:02

HarryHippo


2 Answers

The easiest solution is to use ImageButton widget:

<ImageButton
    (...)
    android:background="@drawable/a_background"
    android:src="@drawable/an_icon"
    />
like image 197
Tomasz Dzieniak Avatar answered Nov 17 '22 16:11

Tomasz Dzieniak


Is there a way to center the drawable without abandoning Button

So you can have both (background & drawable) by using ImageView as below: (So No need to use Button)

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/an_icon"
    android:background="@drawable/a_background" />

For OnClick of ImageView:

findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
});
like image 23
Sagar Shah Avatar answered Nov 17 '22 16:11

Sagar Shah