gpt4 book ai didi

android - 从 xml 文件调用颜色

转载 作者:行者123 更新时间:2023-11-29 00:32:38 25 4
gpt4 key购买 nike

如果我在 res/values/colors 中有一个自定义颜色的 xml 文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources>
<drawable name="red">#ff0000</drawable>
<drawable name="blue">#0000ff</drawable>
<drawable name="green">#00ff00</drawable>
</resources>

我如何在其他代码中使用它的颜色或其他值?

我如何使用这些作为参数?像这样的东西:

    int green = context.getResources().getColor(R.color.green);
g.drawRect(1, 1, 181, 121, green);

在 logcat 中给出错误并使程序崩溃。所以如果 colors.xml 在 res/values/并且我导入了上下文如何使用绿色,例如在参数中?

最佳答案

首先,将 xml 中的 drawable 更改为 color

然后你需要有上下文。它是这样的:

context.getResources().getColor(R.color.green);

它返回一个 int 颜色值。

编辑:

对于其他值,请参阅此处的函数:

http://developer.android.com/reference/android/content/res/Resources.html

我喜欢一次获取所有 xml 颜色并从那里传递它们,这样我就不会一遍又一遍地输入上面的内容。不确定这是否被认为是最佳实践。

如果你想在 Paint 中使用它,它可以是:

// Declare this at the beginning:
Paint green paint;
// This goes in the constructor:
greenPaint = new Paint();
greenPaint.setColor(context.getResources().getColor(R.color.green));
// then draw something in onDraw, for example:
canvas.drawRect(5,5,5,5, greenPaint);

如果你想在多个Paints等中使用它,将它保存为一个int:

int greenNum = context.getResources().getColor(R.color.green);

关于android - 从 xml 文件调用颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com