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:
The res/values folder is used to store the values for the resources that are used in many Android projects to include features of color, styles, dimensions etc. Below explained are few basic files, contained in the res/values folder: colors.
Default resources are items that are not specific to any particular device or form factor, and therefore are the default choice by the Android OS if no more specific resources can be found. As such, they're the most common type of resource to create.
drawable for all drawable resources) and for each resource of that type, there is a static integer (for example, R. drawable. icon ). This integer is the resource ID that you can use to retrieve your resource.
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).
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With