I am making a simple application and I find that I am not able to change the background to a layout 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 through a String. Something like that:
You have to use, without the image extension, 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 the previous parameter is already specified.
- defPackage: The specific package from where you want to obtain said resource.