Set image as a layout background indicating the name of the image on a String


I am making a simple application and I find that I am not able to change the background to a layout by indicating the name of the image in question by String.

The code I have is this:


Where "ff" is the name of the image that I already have saved as a resource ("ff.jpg"). This is how it works perfectly. What I would like is for that "ff" to be supplied by means of a String. Something like this:

asked by Frandalf 26.12.2016 в 14:42

1 answer


You have to use, without the extension of the image, in this case:

String miString = "ff";

int resource = getResources().getIdentifier(miString, "drawable", getPackageName());

According to the android documentation:


getResource: Returns an instance of the resources for the application package.   getIdentifier: Returns a resource identifier for a specific name. The parameters are:

  • name: Resource name
  • defType: The type of resource, this is optional in the case that in the previous parameter is already specified.
  • defPackage: The specific package from where you want to get that resource.
answered by 26.12.2016 / 14:44