how to set materialButton icon to the center

2019-05-03 19:14发布

I am using supportLibrary = "28.0.0-beta01" version.
Here is my code in .xml file:

<android.support.design.button.MaterialButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:icon="@drawable/ic_my_orders"
    app:iconGravity="textStart"
    android:gravity="center"/>

To my code icon of the drawable locating left side of the button. I want to set button to the center. I want to achieve this result enter image description here


Edit

I don't need to any custom views or hard coded things. If this is a bug (app:iconGravity), I will wait next release.

EDIT

The bug fixed in the version 28.0.0-rc01,just change the version.

3条回答
Bombasti
2楼-- · 2019-05-03 19:40

You can use width to wrap_content so it matches your text. And layout_gravity instead of gravity to set the button its own gravity (and not its childs).

<android.support.design.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:icon="@drawable/ic_my_orders"
    app:iconGravity="textStart"
    android:layout_gravity="center"/>
查看更多
做自己的国王
3楼-- · 2019-05-03 19:51

The code snippet you have in your original question is correct. This has been identified as a bug and will be fixed in the upcoming release.

查看更多
成全新的幸福
4楼-- · 2019-05-03 19:51

UPDATED

Try this code to set left padding of button to make it center.

 <android.support.design.button.MaterialButton
    android:id="@+id/material_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:gravity="center_vertical|start"
    android:text="CENTER"
    android:textColor="@android:color/white"
    app:icon="@drawable/ic_location_on_accent_24dp"
    app:layout_constraintBottom_toBottomOf="parent" />

JAVA

 final MaterialButton button = root_view.findViewById(R.id.material_button);
 button.post(new Runnable() {
        @Override
        public void run() {

            int width = button.getWidth();
            button.measure(0,0);
            int paddingleft = (width - button.getMeasuredWidth() + 50)/2; //50 drawable width
            button.setPadding(paddingleft,0,0,0);
        }
    });

OUTPUT
enter image description here

查看更多
登录 后发表回答