简体   繁体   English

设置R.drawable的变量

[英]Set variable for R.drawable

At the moment I set a marker image for google maps on android like this: 目前,我在Android上为Google地图设置了标记图像,如下所示:

.icon(BitmapDescriptorFactory.fromResource(R.drawable.mon1))

Where mon1 is the name of the corresponding to a image called mon1.png in drawable folder. 其中mon1是对应于可绘制文件夹中名为mon1.png的图像的名称。

How can I do it like this: 我该怎么做:

 String imagename="blablaimage";

.icon(BitmapDescriptorFactory.fromResource(R.drawable.imagename))

If you click over R.drawable.mon1 , you'll find an int declared with the name mon1 in R.java class. 如果单击R.drawable.mon1 ,则会在R.java类中找到一个声明为mon1的int。 Everything resides in R class is basically an int. 所有驻留在R类中的东西基本上都是一个int。 That said, you can't declare variable imagename as String to begin with. 就是说,您不能将变量imagename声明为String开头。 It must be int. 它必须是int。

Everything generates in R.java class is auto generated by Android itself. R.java类中生成的所有内容均由Android本身自动生成。 Once you put some resources in appropriate directory, R.java generates corresponding resource int within so that it can be invoked from Java-end. 一旦将一些资源放在适当的目录中,R.java就会在其中生成相应的资源int,以便可以从Java端调用它。

Bottom line, if you have an image called blablaimage somewhere in your drawable, you can (at best) do this, 底线是,如果在可绘制对象的某处有一个名为blablaimage的图像,则可以(最多)执行此操作,

int imagename= R.drawable.blablaimage;

.icon(BitmapDescriptorFactory.fromResource(imagename))

It is not possible to do what you suggested. 无法执行您建议的操作。

Instead, a possible workaround might be to use the following function: 而是,一种可能的解决方法可能是使用以下功能:

public int getDrawableId(String name){
        try {
            Field fld = R.drawable.class.getField(name);
            return fld.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

and use like: 并使用像:

 String imagename="blablaimage";

.icon(BitmapDescriptorFactory.fromResource(getDrawableId(imagename)));

Another possibility using Resources.getIdentifier : 使用Resources.getIdentifier另一种可能性:

.icon(BitmapDescriptorFactory.fromResource(
   context.getResources().getIdentifier(imagename, "drawable", "com.mypackage.myapp"); 
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM