【问题标题】:Get resources id from a string [duplicate]从字符串中获取资源ID [重复]
【发布时间】:2016-06-02 17:47:35
【问题描述】:

我该怎么做?

for(String name: nameArray){    
    ImageView i = new ImageView(this);   
// the line below does not work of course 
    i.setBackgroundImage(R.drawable.name);
//do some stuff
}

我已经搜索了一些解决方案,但其中大多数都涉及我没有的整数 ID

【问题讨论】:

    标签: android android-resources


    【解决方案1】:

    请检查下面的代码好吗?

    我不完全确定它是否有效。但是,我知道您可以使用返回 ID 的Resources.getIdentifier()。但是,我不确定它是否也适用于 drawable

    for(String name: nameArray){    
        ImageView i = new ImageView(this);
        i.setBackgroundImage(getResources().getIdentifier(name, "drawable", getPackageName()));
    }
    

    【讨论】:

    • 这应该可以,但是,可能需要对 ImageView 进行一些处理,否则只会显示最后一个可绘制对象
    猜你喜欢
    • 2011-05-24
    • 2018-03-23
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多