问题
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