Dynamic Resource Loading Android

后端 未结 3 1758
长发绾君心
长发绾君心 2020-11-29 01:47

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 fi

相关标签:
3条回答
  • 2020-11-29 02:02

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 02:03

    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.

    0 讨论(0)
  • 2020-11-29 02:08

    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).

    0 讨论(0)
提交回复
热议问题