AndreasK AndreasK - 3 months ago 22
Android Question

Set variable for R.drawable

At the moment I set a marker image for google maps on android like this:

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


Where
mon1
is the name of the corresponding to a image called
mon1.png
in drawable folder.

How can I do it like this:

String imagename="blablaimage";

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

Answer

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)));