我编写了一个依赖资源中定义的颜色的应用程序。有些是直接在布局 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/