Android .xml文件:为什么预定义的颜色对我不起作用?

mmo*_*mmo 29 android

当我看到misc.Android的教程和例子,当涉及到指定的颜色我经常看到这样的常数@color/red@color/black使用等.出于一些奇怪的原因,永远不会为我工作!我总是需要使用"#RGB",#ARGB,...,#AARRGGBB表示法指定颜色.

很快,当我尝试使用任何这些助记符常量,例如"@ color/red"时,我收到如下错误消息:

[...] C:\Users\mmo\Test\res\drawable\edit_text.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@color/orange').
[...] C:\Users\mmo\Test\res\drawable\myDrawable.xml:3: error: Error: No resource found that matches the given name (at 'drawable' with value '@color/black').
[...] C:\Users\mmo\Test\res\drawable\myDrawable.xml:4: error: Error: No resource found that matches the given name (at 'drawable' with value '@color/black').
[...] C:\Users\mmo\Test\res\drawable\myDrawable.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@color/green').
[...] C:\Users\mmo\Test\res\drawable\myDrawable.xml:6: error: Error: No resource found that matches the given name (at 'drawable' with value '@color/black').
Run Code Online (Sandbox Code Playgroud)

为什么会这样?为什么我不能使用这些预定义的常量?我需要在它们前面添加一些包名称(我试过@android:color/red但只会导致不同的错误)?我需要自己指定这些颜色吗?如果是这样:怎么样和在哪里?任何想法或建议?

迈克尔

Rom*_*Guy 62

如果您想使用Android平台中预定义的颜色,则语法为@android:color/white.开头的"android:"表示资源不是您的应用程序的一部分.

  • 实际上,我只需要学习,这个DOES有效,但显然只有"颜色"@android:颜色/白色和@android:颜色/黑色被定义.我试过的所有其他人(如@android:颜色/红色,@ android:颜色/绿色,@ android:颜色/蓝色等)都会产生错误.很奇怪! (13认同)
  • 如果定义了这些,请http://developer.android.com/reference/android/graphics/Color.html#constants,我希望也可以预先定义XML值. (8认同)
  • 不,正如我上面已经写过的那样:这不起作用 - 至少不适合我.是否有任何特殊设置或"导入"(或其他)使其工作? (3认同)

dwa*_*esh 29

"colors.xml"是否已添加到res/values文件夹中,其中定义了这些颜色常量?

  • 我现在在我的应用程序中创建了这样一个文件,并在那里定义了一堆默认颜色,现在我确实可以使用这样的命名颜色.显然,我所看到的所有这些例子都假定存在这样一个文件而没有明确说明.因此,我错误地得出结论,这些值是预定义的. (5认同)

Sun*_*ngh 6

颜色XML文件位于values文件夹中,其中必须包含颜色值.within resources标记.

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<color name="green">#00ff00</color>
Run Code Online (Sandbox Code Playgroud)


And*_*ndy 5

确保您的颜色 XML 文件位于文件夹中,而不是颜色文件夹中。

所以你应该...

/colors.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <color name="red">#FF0000</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

而不是这个...

颜色/colors.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <color name="red">#FF0000</color>
</selector>
Run Code Online (Sandbox Code Playgroud)

请注意,标签是资源,而不是选择器