Reputation: 196
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))
Upvotes: 1
Views: 1947
Reputation: 20211
Another possibility using Resources.getIdentifier
:
.icon(BitmapDescriptorFactory.fromResource(
context.getResources().getIdentifier(imagename, "drawable", "com.mypackage.myapp");
));
Upvotes: 1
Reputation: 6160
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)));
Upvotes: 2
Reputation: 6704
If you click over R.drawable.mon1
, you'll find an int declared with the name mon1 in R.java class. Everything resides in R class is basically an int. That said, you can't declare variable imagename
as String to begin with. It must be int.
Everything generates in R.java class is auto generated by Android itself. Once you put some resources in appropriate directory, R.java generates corresponding resource int within so that it can be invoked from Java-end.
Bottom line, if you have an image called blablaimage somewhere in your drawable, you can (at best) do this,
int imagename= R.drawable.blablaimage;
.icon(BitmapDescriptorFactory.fromResource(imagename))
Upvotes: 1