how to set materialButton icon to the center

女生的网名这么多〃 提交于 2019-12-04 02:10:42

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.

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"/>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!