首页 > 解决方案 > 引用具有 alpha 属性的颜色文件时,形状 XML 中的渐变颜色显示错误

问题描述

新建一个项目,只将主activity的背景改为shape梯度xml文件,这里的梯度android:centerColor是指?attr/colorAccent带alpha值的。问题出现了。无论你设置什么颜色,它都会变成粉红色

这里的图像

但是如果android:centerColor梯度中的值是硬编码,就不会出现问题。

的编辑器界面mask.xml可以正常显示,但是在设备或AVD上运行时中间的颜色变成粉红色。

这里的图像

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@drawable/mask"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

@drawable/mask.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="90"
        android:centerColor="@color/alpha_95"
        android:endColor="?attr/colorOnPrimary"
        android:startColor="?attr/colorOnPrimary"
        android:type="linear" />
</shape>

@color/alpha_95.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:alpha="0.95" android:color="?attr/colorAccent" />
</selector>

标签: androidxml

解决方案


推荐阅读