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

3

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:

fondo.setBackgroundResource(R.mipmap.ff);

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:

miString="ff.jpg";
fondoJuego.setBackgroundResource(R.mipmap.miString);
    
asked by Frandalf 26.12.2016 в 14:42
source

1 answer

4

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

String miString = "ff";

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

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
source