Accessing the R app class from my android library

I am developing a library that needs to access the layout elements of an application that implements it. The only way I know how to do this is to reflect. In other words, if I create a constructor for my Library API like this:

public MyLibraryAPI(String packageName) {
    Class appR = Class.forName(String.format("%s.R", packageName));
    ...
}

      

And the developer will instantiate the library with their package name as a parameter in the constructor.

Ultimately I need my inner classes to know the Android views used in the developers layout (.xml files) - both id and type. Is there a way to achieve this without reflection and avoid the overhead? I'm sure this cannot be done, but ask if there is an expert who sees what I don't.

EDIT: Also, proguard by default obfuscates the code for protection, but as a consequence does not provide the JVM with a means of reflection at runtime, so if I use reflection I have to ask the developer to disable proguard obfuscation for his or her R class, which is is a wreck.

+3


source to share


1 answer


Reflection on Android is extremely expensive. Some well-meaning and popular libraries such as Roboguice have dropped in part due to reflection performance.

I suspect some code generation is the correct solution. Dagger 2 , Butter Knife, and Data Binding Library are all successful examples of Android libraries that use code generation. Since the data binding library does validations in XML, it should be available to the code generation libraries at this build step, and you can base your implementation on that: here's a link to the source jars in Maven Central .



Also, yes, there seems to be some trade-off between ease of use and difficulty to implement. If you force your consumers to annotate their classes with their annotations, it becomes more difficult to use, but it is probably much easier for you to implement. If you limit yourself to validating the XML and the generated file R

and generating code from just that, I think your job will be much more difficult. On the other hand, the use of annotations has become quite common and may not be such a problem for your users.

Good luck!

+1


source







All Articles