将图标放在 MaterialButton 中的文本顶部

Placing icon on top of text in MaterialButton

我想将图标放在 materialButton 的顶部,如下所示:

但是我在 MaterialButton 中找不到任何属性来将 app:icon 的重力设置为顶部。 我只能将它设置为开始或结束。 有没有什么方法可以设置创建一个类似的按钮,而无需将 Vertical LinearLayout 与 ImageView 和 TextView 一起使用?

您可以为此使用 android:drawableTop 属性

Note : This is not only restricted for the MaterialButton you can use it on TextViews and other views also

示例代码:

<com.google.android.material.button.MaterialButton
    android:layout_width="match_parent"
    android:text="@string/app_name"  <!-- Your Text -->
    android:drawableTop="@drawable/ic_launcher_background" <!-- Your Icon -->
    android:layout_height="wrap_content"/>

您可以使用 iconGravity="textTop".

    <com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.TextButton"
        app:icon="@drawable/ic_add_24px"
        app:iconGravity="textTop" />

注意: 版本至少为1.3.0-alpha02.