Dynamic Resource Loading Android
Asked Answered
P

3

36

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

More specifically, I want to have a XML that references a bunch of other XML files in the application apk. For the purpose of explaining, let's say the main XML is main.xml and the other XML are file1.xml, file2.xml and fileX.xml. What I want is to read main.xml, extract the name of the XML I want (fileX.xml), for example, and then read fileX.xml. The problem I face is that what I extract form main.xml is a string and I can't find a way to change that to R.raw.nameOfTheFile.

Anybody has an idea?

I don't want to:

  • regroup everything in one huge XML file
  • hardcode main.xml in a huge switch case that links a number/string to the resource ID
Paduasoy answered 6/9, 2010 at 4:5 Comment(1)
i faced a similar problem but I am not getting any accepted answer for this. Can anybody start bounty for this question?Kimberly
I
61

I haven't 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 (R.id) of the resource. You would need to replace drawable with something else, maybe raw or layout (untested).

Imprint answered 6/9, 2010 at 4:42 Comment(3)
Thanks for the answer that work great. For those in the same case here is a good explanation on the subject (once I had the name of the function it was simple): getResources().getIdentifier("fileX", "raw", application package);Paduasoy
Dead link? @JasonRogers Ah, nvm - it should be anddev.org/…Bamby
no not dead link casperOne removed my post and changed it to a comment without taking the time to do it correctly (aka broken link) here is the link: anddev.org/tinytut_-get_resources_by_name__getidentifier-t460.htmlPaduasoy
M
26

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);
    }
}
Mahayana answered 9/12, 2011 at 22:11 Comment(1)
Very useful, thanks, but not ever we would want a string. sometimes a stream would be better.Pontormo
A
7

There is another method:

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

According to this blog it's 5x times faster than using getIdentifier.

Avivah answered 25/3, 2016 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.