【问题标题】:How can I get a resource by name based on a string variable?如何根据字符串变量按名称获取资源?
【发布时间】:2012-06-01 05:29:18
【问题描述】:

我想做

String childImg = "childIcon";
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.????, 0, 0, 0);

它需要一个 int 但我有一个字符串。我该如何解决这个问题?

【问题讨论】:

标签: android


【解决方案1】:

我用它来获取可绘制的 id

getResources().getIdentifier(childImg, "drawable", getPackageName())

【讨论】:

    【解决方案2】:

    使用getIdentifier()

    int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
    

    【讨论】:

    【解决方案3】:

    这样做:

    String childImg = "childIcon";
    int id = getResources().getIdentifier(childImg, "drawable", getPackageName())
    textView.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0);
    

    【讨论】:

    • 是的,有一点,因为它必须遍历所有资源元素才能找到正确的元素。
    • 因此,如果您要进行多次调用,最好在单例类中使用一个整数数组...对吗?
    • 是的,确实如此。但是,如果您没有大量资源元素列表,那么您可能会忽略性能问题
    • 由于某种原因无法正常工作。图片只是没有出现
    【解决方案4】:
    textView.setCompoundDrawablesWithIntrinsicBounds(Resources.getIdentifier(childImg), 0, 0, 0);
    

    【讨论】:

    • 由于某种原因无法正常工作。图片只是没有出现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多