【问题标题】:Can't create gradient material design button [duplicate]无法创建渐变材质设计按钮[重复]
【发布时间】:2019-11-05 23:52:40
【问题描述】:

我正在尝试创建带有 backgroundTint 渐变的按钮。

我在 drawable 中定义了我的渐变:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

    <gradient
            android:centerX="50%"
            android:centerY="50%"
            android:endColor="#308c35"
            android:gradientRadius="100dp"
            android:startColor="#66BB6A"
            android:type="linear" />

    <corners android:radius="22dp" />

</shape>

现在我正在尝试将其用作按钮的值:

    <com.google.android.material.button.MaterialButton
            android:id="@+id/material_unelevated_button"
            style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
            android:layout_width="160dp"
            android:layout_height="58dp"
            android:layout_marginBottom="84dp"
            android:text="@string/button_start_text"
            app:backgroundTint="@drawable/main_gradient"
            app:cornerRadius="14dp"
            app:iconPadding="3dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.498"
            app:layout_constraintStart_toStartOf="parent"
            app:strokeWidth="0dp" />

很遗憾,它不适用于 backgroundTint。我正在使用材质主题,因此只有更改 backgroundTint 值才能更改按钮的外观。我找不到解决方案,我尝试将 android:background 和所有其他与背景相关的选项设置为渐变,但没有效果。

【问题讨论】:

  • 试试下面的代码
  • 你做不到。 BackgroundTint 使用颜色不是可绘制的,MaterialButton 也管理自己的背景可绘制

标签: android material-design


【解决方案1】:

这行不通。不知何故,我也尝试过,它在材质按钮中的渐变不起作用,它与材质设计的内部有关。

【讨论】:

    【解决方案2】:

    很简单:

    渐变.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
       <gradient
            android:centerX="50%"
            android:centerY="50%"
            android:endColor="#308c35"
            android:gradientRadius="100dp"
            android:startColor="#66BB6A"
            android:type="linear" />
    
      <corners android:radius="@dimen/dp_10" />
    </shape>
    

    还有你的按钮:

    <Button
        android:id="@+id/btn_confirm"
        android:layout_width="160dp"
        android:layout_height="58dp"
        android:layout_marginBottom="84dp"
        android:text="@string/button_start_text"
        android:layout_weight="1"
        android:background="@drawable/gradient" >
    

    【讨论】:

    • 它不起作用,因为如果您使用的是 Material 组件主题,则 之间没有区别。检查this question
    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 2019-03-25
    • 2016-03-10
    • 1970-01-01
    • 2017-07-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多