how to set materialButton icon to the center

好久不见. 提交于 2020-01-12 13:50:35

问题


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


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.


回答1:


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.




回答2:


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:


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



来源:https://stackoverflow.com/questions/51633118/how-to-set-materialbutton-icon-to-the-center

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