java - colors.xml 资源不起作用

标签 java android android-xml android-resources

我在我的 Android 应用程序中的/res/values/colors.xml 下创建了一个 colors.xml 文件。内容是……

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Green">#00ff00</color>
</resources>

我尝试使用...更新我的 TableRow 的背景

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(R.color.Green);

这不会将其设置为绿色,而是灰色。无论我向 colors.xml 文件添加什么值,它始终是相同的灰色。然而,这确实有效......

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(android.graphics.Color.GREEN);

我的 colors.xml 有问题吗?

最佳答案

你应该改用这个:

TableRow test = (TableRow)findViewById(R.id.tableRow2);
test.setBackgroundColor(getResources().getColor(R.color.Green));

不幸的是,资源 ID 和颜色具有相同的类型:int。您应该通过 getColor() 从资源中获取颜色值并将该值用作颜色。当您使用资源 ID 作为颜色时。

关于java - colors.xml 资源不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641210/

相关文章:

java - 将新对象添加到数组时出现 NullPointerException

java - 如何在android中循环动态振动模式?

android - ListPreference 数组条目禁用复选框首选项

Android MaterialButton 在 XML 中设置检查数据绑定(bind)

java - 强制 android libgdx 进入沉浸模式

AndroidX 首选项屏幕偏离中心

Java Http - Post header 内​​容长度

java - 同步对象并更改其字段之一

android - 如何在 Jacoco 报告生成中公开 "sourceDirectories"?

java - 如何用Solr管理 "paging"?