Reputation: 22750
I need to add drawable to my button and added drawableLeft to it. If button's width is set to wrap_content, then everything is fine and looks good. But if I set custom width to my button then drawableLeft image goes away from button's caption to left edge of the button. Is this somekind of a design bug in android? How can I fix this to let button look the same on custom width?
Regards, evilone
Upvotes: 0
Views: 3118
Reputation: 65
I had this problem just right now, but I found out that you just need to set android:padding to the button. That way you push the picture away from left side of the button. Check this code:
`<Button
android:id="@+id/button1"
android:layout_width="170dp"
android:layout_height="50dp"
android:layout_below="@+id/txt1"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:background="@drawable/button"
android:drawableLeft="@drawable/icon"
android:drawablePadding="20dp"
android:minHeight="40dp"
android:onClick="onClick"
android:padding="40dp"
android:text="@string/string1"
android:textSize="16sp" />`
Upvotes: 1
Reputation: 4252
Just set android:gravity="center_vertical"
to your button attributes.
<Button
android:id="@+id/button_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_btn_icon"
android:drawablePadding="5dp"
android:text="Button"
android:gravity="center_vertical" />
Upvotes: 1
Reputation: 54725
Seems that x-position of the drawableLeft
depends on left padding and x-scroll position: source. So that's by-design behavior. I think you'd better use SpannableString
and ImageSpan
classes to display an image to the left of the button's text:
final SpannableStringBuilder builder = new SpannableStringBuilder("\uFFFC");
builder.setSpan(new ImageSpan(getResources.getDrawable(R.drawable.your_drawable)),
0, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(getString(R.string.your_string));
textView.setText(builder);
Also, you can use Html.fromHtml()
method to build Spannable
from HTML. But in this case you need to implement Html.ImageGetter
interface to load images from resources.
EDIT: There's a way to do a button-like widget using only XML:
<LinearLayout
android:layout_width="200dip"
android:layout_height="wrap_content"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:background="@android:drawable/btn_default">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:src="@drawable/button_icon"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:text="@string/button_text"/>
</LinearLayout>
Upvotes: 3