colors.xml资源不起作用

b10*_*ard 15 java android android-xml android-resources

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Green">#00ff00</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

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

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(R.color.Green);
Run Code Online (Sandbox Code Playgroud)

这不会将其设置为绿色,而是灰色.无论我添加到colors.xml文件的值是什么,它总是相同的灰色.不过这确实有用......

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(android.graphics.Color.GREEN);
Run Code Online (Sandbox Code Playgroud)

我的colors.xml有问题吗?

ina*_*ruk 22

您应该使用此代替:

TableRow test = (TableRow)findViewById(R.id.tableRow2);
test.setBackgroundColor(getResources().getColor(R.color.Green));
Run Code Online (Sandbox Code Playgroud)

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