Reputation: 39810
I want the text centered in the Button
. But whenever I add android:drawableLeft
xml attribute to the Button
, it offsets the text. How can I fix that?
The only way I managed to fix it is by setting a negative number in android:drawablePadding
:
But I'm looking for a cleaner solution to achieve it.
Upvotes: 2
Views: 1302
Reputation: 3165
Unfortunately there's no clean way to do this. One fairly straightforward way is to set a transparent ColorDrawable of equal size on the opposite side of the button.
val drawableSize = button.height // adjust this as desired of course
realDrawable.setBounds(0, 0, drawableSize, drawableSize)
val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
setBounds(0, 0, drawableSize, drawableSize)
}
button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)
Upvotes: 0
Reputation: 39810
So I ended up going with the lesser of the evils, and that's placing the drawable and the text inside RelativeLayout
:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Button.ButtonGray"
android:id="@+id/share_button">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_share"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_centerInParent="true"
style="@style/TextNormalWeight"
android:text="@string/post_share"/>
</RelativeLayout>
The RelativeLayout
then receives click events and acts and looks like a button.
Upvotes: 1
Reputation: 39836
unfortunately that is the Button
behaviour and I agree with you that negative padding is kind of a dirty hack, so I'll propose two other hacks that to me sounds a little less dirty because they rely on expected behaviour (negative padding although works it's not by design):
android:paddingRight
on the button to the size of the drawablesUpvotes: 1