使用 alpha 在材质按钮上设置 backgroundTint 在正常和按下状态下具有奇怪的视觉效果

Abh*_*hek 7 android material-design material-components material-components-android

我在我的项目中使用 Material Buttons 并尝试使用 alpha 值设置 backgroundTint。

<!-- background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/black" android:alpha="0.60"/>
</selector>

<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="Sign in"
        app:backgroundTint="@color/background_tint" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

然而,生成的按钮在正常状态下看起来很奇怪,按下时甚至更奇怪。
在此处输入图片说明
当我将 backgroundTint 设置为特定的灰色阴影(例如 #777777)时,我没有看到这个问题。为什么 alpha 值会发生这种情况?

Ham*_* XD 0

您很可能看到了下面的阴影。看起来 Material Design 的阴影很奇怪。感觉阴影只在侧面,因为无论如何你都不应该看到它们。

您可以通过使用未升高的按钮 ( style="@style/Widget.MaterialComponents.Button.UnelevatedButton") 或尝试重新创建没有 alpha 的灰色阴影来修复它(可以通过屏幕截图没有阴影怪异的部分并使用吸管来获取 RGB 颜色)

另外,您似乎正在尝试更改选择器的颜色。可以通过使用 来实现app:rippleColor="@color/yourRippleColor"背景色调根据材质组件文档(材质组件:按钮)更改按钮本身的颜色。调整 Alpha 会调整颜色的不透明度,使按钮更加透明/不透明,使您能够看到其下方。