Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center icon in a MaterialButton which has no text?

I'm using the latest version of the com.google.android.material:material library (i.e. 1.1.0-alpha03) and I have a MaterialButton defined with an icon and no text as follows:

I was hoping the MaterialButton would be rendered as a square with the icon centred within it but instead the MaterialButton is rendered as follows:

MaterialButton with iconGravity value of start

If I change the iconGravity value to "textStart" the MaterialButton is rendered as follows:

MaterialButton with iconGravity value of textStart

This is a slight improvement to the positioning of the icon but the icon is still a little off centre. If I change the insetLeft, insetRight, insetTop and insetBottom values to 0dp the MaterialButton is rendered as follows:

enter image description here

This is an improvement to the shape of the button but the icon is still a little off centre.

Anyone know whether there's something further I can do to centre the icon within the MaterialButton?

like image 292
Adil Hussain Avatar asked Feb 15 '19 16:02

Adil Hussain


People also ask

How can set image in center of button in Android?

Create a RelativeLayout "wrap_content" with the button image as the background or the button itself as the first element of the layout. Get a LinearLayout and set it to "layout_centerInParent" and "wrap_content". Then set your Drawable as an Imageview.


1 Answers

Found it. The attribute I was missing was app:iconPadding="0dp".

So, from my experiments, the minimum attributes needed to create a square MaterialButton which has a centred icon and no text is the following:

<com.google.android.material.button.MaterialButton     android:layout_width="52dp"     android:layout_height="52dp"     android:insetLeft="0dp"     android:insetTop="0dp"     android:insetRight="0dp"     android:insetBottom="0dp"     app:icon="@drawable/icon_next"     app:iconGravity="textStart"     app:iconPadding="0dp" /> 

These attributes produce a MaterialButton as follows:

MaterialButton with square shape and centred icon

like image 157
Adil Hussain Avatar answered Sep 23 '22 15:09

Adil Hussain