【问题标题】:Retrieve color programmatically from R.color从 R.color 以编程方式检索颜色
【发布时间】:2014-10-27 09:56:26
【问题描述】:

我有一个包含许多 TextView 的 ListView,一个 TextView 应该包含不同的背景颜色,具体取决于检索到的数据。

因为我不想硬编码我使用 R.color 设置颜色的颜色。这很好用,但我必须手动检查每种颜色,因为我注意到能够像 HashMap 一样获得颜色。所以我的第一次尝试是这样的:

    switch(line) {
    case "1":
        lineColor = context.getResources().getColor(R.color.line1);
    case "2":
        lineColor = context.getResources().getColor(R.color.line2);
    ....
    ....
    }

这似乎与干净的代码相去甚远,所以我尝试了一种不同的方法,使用字符串数组:

<string-array name="line_color_names">
    <item>1</item>
    <item>2</item>
    ....
</string-array>

<string-array name="line_color_values">
    <item>#e00023</item>
    <item>#ef9ec1</item>
    ....
</string-array>

在我的 AdapterClass 中,我刚刚创建了一个 HashMap 并将这个字符串数组放在一起:

    String[] line_color_names = context.getResources().getStringArray(
            R.array.line_color_names);
    String[] line_color_values = context.getResources().getStringArray(
            R.array.line_color_values);

    lineColors = new HashMap<String, String>();
    for (int i = 0; i < line_color_names.length; i++) {
        lineColors.put(line_color_names[i], line_color_values[i]);
    }

所以我的问题是:这是实现这一目标的唯一方法还是还有另一种方法,理想情况下是直接从 R.color 获取颜色?

提前致谢!

【问题讨论】:

  • 好问题有足够的细节!
  • 顺便说一句,颜色名称是按顺序排列的,对吧?
  • @PareshMayani 没错。谢谢你:)

标签: android colors


【解决方案1】:

您可以通过资源名称 (R.color.foo) 获取颜色 ID 并在运行时解析它:

public int getColorIdByResourceName(String name) {
  int color;
  try {
    Class res = R.color.class;
    Field field = res.getField( name );
    int color = field.getInt(null);
  } catch ( Exception e ) {
    e.printStackTrace();
  }
  return color;
}

然后

int colorId  = getColorIdByResourceName("foo21");
int colorVal = getResources().getColor(getColorIdByResourceName("foo21"));

【讨论】:

  • 我以前是Integer,但我在发帖前更改了它。
  • 此代码中的错误。诠释颜色=空;不会工作。还有 color = getColorValueByResourceName("R.color.foo21");是错的。它应该是 color = getColorValueByResourceName("foo21");
  • 是的。 “欲速则不达”:/
  • 我会让方法返回 Color 对象。
  • 我也是,但那是 OP 练习 :)
【解决方案2】:

您的第二个解决方案似乎不错,并且不完全是 hack。你应该找到这个。 但是,如果您动态获取颜色名称,那么此代码对您来说可能会很方便。

public static int getColorIDFromName(String name)
{
    int colorID = 0;

    if(name == null
            || name.equalsIgnoreCase("")
            || name.equalsIgnoreCase("null"))
    {
        return 0;
    }

    try
    {
        @SuppressWarnings("rawtypes")
        Class res = R.color.class;
        Field field = res.getField(name);
        colorID = field.getInt(null);
    }
    catch(Exception e)
    {
        Log.e("getColorIDFromName", "Failed to get color id." + e);
    }

    return colorID;
}

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 2015-07-01
    • 2010-09-13
    • 1970-01-01
    • 2015-12-06
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多