【问题标题】:how to align text and icon left on MaterialButton (with icon directly after text)?如何对齐 MaterialButton 上左侧的文本和图标(文本后直接带有图标)?
【发布时间】:2021-08-19 12:52:22
【问题描述】:

我想创建带有文本和图标的按钮,都左对齐。 我正在使用app:iconGravity="textEnd" 将图标直接放在按钮文本之后,但是如果我使用android:gravity="left" 将文本位置更改为左侧,则图标将保持在旧的居中位置

我的布局-xml:

 <com.google.android.material.button.MaterialButton
        android:id="@+id/listentry_button"
        style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
        app:icon="@drawable/ic_arrow_straight_right"
        app:iconGravity="textEnd"
        android:gravity="left"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="@string/account_data_personal_data"
        android:textColor="@color/primaryTextColor"
        app:iconTint="@color/secondaryColor"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

知道如何使用材料按钮来实现这一点,还是不可能?

【问题讨论】:

  • 为什么不尝试使用线性布局而不是 Material 按钮?

标签: android material-components-android


【解决方案1】:
<com.google.android.material.button.MaterialButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="My button"
            app:icon="@drawable/ic_arrow"
            app:iconGravity="textEnd"
            />

上面的代码可以给你以下结果

<com.google.android.material.button.MaterialButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="My button"
            android:gravity="left|center_vertical"
            app:icon="@drawable/ic_arrow"
            app:iconGravity="textStart"
            />

上面的代码可以给你以下结果

【讨论】:

    【解决方案2】:

    您是否尝试更改布局宽度以包裹内容?

    android:layout_width="wrap_content"
    

    【讨论】:

    • 好的,那就可以了,谢谢。但我想用按钮填充整个可用宽度(因为它的点击监听器),所以我不能使用这个解决方案。我想我必须用 textView 和 image 创建布局来解决这个问题。
    • 您可以尝试将按钮中的文本居中。
    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2019-11-22
    • 2016-10-02
    • 1970-01-01
    • 2020-11-09
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多