android:textColor 不再适用于 Marshmallow

标签 android android-styles android-6.0-marshmallow cyanogenmod

我编写了一个依赖资源中定义的颜色的应用程序。有些是直接在布局 XML 文件中设置的,有些是在代码中设置的。示例:

res/values/styles.xml 中的颜色定义:

<color name="orvGyro">#33B5E5</color>

布局:

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/dotSpace"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textColor="@color/orvGyro" />

代码中的颜色:

accStatus.setTextColor(getResources().getColor(R.color.somecolor));

该应用程序以 API 17 为目标。在 Lollipop 之前,它运行完美,显示正确的颜色。迁移到 Marshmallow (Cyanogenmod 13) 后,所有这些颜色都显示为橙色。在 Java 代码而非资源中定义的其他颜色似乎可以正确显示。

我尝试将目标 API 更改为 23 并为 API 21+ 添加样式,但无济于事。

这是怎么回事?这是 CyanogenMod13 中的错误,还是我做错了什么?

编辑: 似乎与从资源中获取颜色无关。如下所示硬编码颜色也会给我橙色文本:

<TextView
    android:id="@+id/textView9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/dotSpace"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textColor="#669900" />

编辑 2: 刚遇到 Android M Developer Preview - TextView android:textColor being ignored .这可以解释我遇到的行为吗?

编辑 3: 当我动态生成内容而不是使用布局时,颜色显示正确。示例:

    TextView newType = new TextView(rilLteCells.getContext());
    newType.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 2));
    newType.setTextAppearance(rilLteCells.getContext(), android.R.style.TextAppearance_Medium);
    newType.setTextColor(rilLteCells.getContext().getResources().getColor(getColorFromGeneration(cell.getGeneration())));
    newType.setText(rilLteCells.getContext().getResources().getString(R.string.smallDot));
    row.addView(newType);

最佳答案

使用ContextCompat类,它是帮助类,用于以向后兼容的方式访问 API 级别 4 之后引入的 Context 中的功能。

accStatus.setTextColor(ContextCompat.getColor(context, R.color.somecolor));

public static final int getColor (Context context, int id)

     Returns a color associated with a particular resource ID

关于android:textColor 不再适用于 Marshmallow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116633/

相关文章:

android - 使用 Theme.MaterialComponents.DayNight.NoActionBar 时,深色主题上的 OverFlow 菜单颜色错误

android - 获取Android API 23及以上版本的当前位置经纬度

android - 如何通过代码编程获取设备的 IMEI/ESN 号码 但是在 android > 6

android - 我的 MenuItem 的 getActionView() 返回 null

android - DatePicker 日历 View

android - 读取文本外观属性

android - 如何避免在 Android M 上处于电池/省电模式时停止我的前台服务

java - Activity android sdk 中的滑动屏幕

java - OkHttp 3.11 和 TLS 1.2 支持

android - 按钮不显示, Material 主题不工作