Android resource dynamic loading

I am trying to find a way to open resources whose name is determined only at runtime.

In particular, I want to have XML that references a bunch of other XML files in the apk application. For the purpose of explanation, let's say the main XML is main.xml and the other XML is file1.xml , file2.xml and fileX.xml . I want to read main.xml , main.xml , extract the XML name I want ( fileX.xml ), and then read fileX.xml . The problem that I am facing is that what I am extracting from the main.xml form is a string and I cannot find a way to change this to R.raw.nameOfTheFile .

Anyone have an idea?

I do not want:

  • regroup everything into one huge XML file
  • hardcode main.xml in the huge case of a switch that associates a number / line with a resource identifier
+31
android
Sep 06 '10 at 4:05
source share
3 answers

I have not used it with raw files or xml layout files, but for drawables I use this:

 getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www"); 

to get the identifier (Rid) of the resource. You will need to replace drawable with something else, perhaps raw or layout (untested).

+53
Sep 06 2018-10-10T00:
source share

I wrote this handy little helper method to encapsulate this:

 public static String getResourceString(String name, Context context) { int nameResourceID = context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName); if (nameResourceID == 0) { throw new IllegalArgumentException("No resource string found with name " + name); } else { return context.getString(nameResourceID); } } 
+23
Dec 09 '11 at 10:11
source share

There is another way:

 int drawableId = R.drawable.class.getField("file1").getInt(null); 

According to this blog is 5 times faster than using getIdentifier.

+6
Mar 25 '16 at 21:16
source share



All Articles