简体   繁体   中英

Listing all of App resources within an Android Library

My aim is to write an android Library that can list all the resources (layouts, drawables. ids, etc.) of the caller application. The caller application need to pass to the library, nothing more than App Name or the package namespace. Eg:

The MyLibrary function:

public void listDrawables(String namespace) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    String resourceNameSpace = namespace + ".R";
    String drawableNamespace = resourceNameSpace + ".drawable";

    final Class drawableClass = Class.forName(drawableNamespace);
    Object drawableInstance = drawableClass.newInstance();
    final Field[] fields = drawableClass.getDeclaredFields();

    for (int i = 0, max = fields.length; i < max; i++) {
        final int resourceId;
        try {
            resourceId = fields[i].getInt(drawableInstance);
            // Use resourceId further
        } catch (Exception e) {
            continue;
    }
}

The caller code (From the App Activity, say com.example.sample.MainActivity.java )

mylibrary.listDrawables("com.example.sample");

I have setup the MyLibrary as a dependent android library for the Sample app.

When this is run, I get this exception inside library at the Class.forName statement:

java.lang.ClassNotFoundException: com.example.sample.R.drawable

I am not able to understand fully, why library can't refer to the class. May be I missed a basic lesson in Java classpath and how build works, but isn't the class already loaded when library runs?

I would also like to know id there is any alternative way to list resources in an external library.

Since Drawable is a inner class, you need to access it by using $ .

String resourceNameSpace = namespace + ".R";
String drawableNamespace = resourceNameSpace + "$drawable";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM