سؤال

I've developed several Android apps now and have created a code base of classes that I frequently use in more than one app. This code is all in a subversion (svn) repository with each app in its own repository. Each app then has svn:externals references for the needed packages (e.g., com.company.android.views). This works great except in the case when the R class has to be imported for custom attributes.

A custom view has an import like this:

import com.company.apps.myapp.R

so that it can have code like this:

attributes.getBoolean(R.styleable.WebImageView_autoload, autoload)

That custom attribute is defined in res/values/attrs.xml:

<declare-styleable name="WebImageView">
    <attr name="autoload" format="boolean" />
    ...others
</declare-styleable>

This works perfectly, but the problem comes when I have a second app that uses this same view. Now I update the import to import com.company.apps.anotherapp.R so that it will work with "anotherapp" and that breaks it with "myapp." When working on several apps at once, this becomes an issue.

My temporary solution has been to check in an update to the applicable classes and then lock the svn:externals to that specific revision. Each app ends up being locked to a different revision, which gets messy fast, but that still seems better than copying the various classes into the app's repo directly.

The only other solution I've thought of it using reflection, something like:

Class class = Class.forName(context.getPackageName() + ".R");
Field[] fields = class.getDeclaredFields();

And then loop through the fields, assigning the ones I care about to variables that are used throughout the class. This seems rather heavy-handed though, especially when we could be talking about several classes needing to do this.

How can I solve this issue? Is there a way to dynamically import the com.company.apps.*.R or to somehow generate a different R class that doesn't depend on the specific app? Or is there some other obvious (or not so obvious) solution I've totally missed?

هل كانت مفيدة؟

المحلول

Took me a while, but I found a good answer: Library Projects.

Structurally, a library project is similar to a standard Android application project. For example, it includes a manifest file at the project root, as well as src/, res/ and similar directories. The project can contain the same types of source code and resources as a standard Android project, stored in the same way. For example, source code in the library project can access its own resources through its R class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top