Best practice: Extending or overriding an Android library project class

前端 未结 7 1740
春和景丽
春和景丽 2020-12-04 15:31

We\'re using an Android Library Project to share core classes and resources across different builds (targets) of our Android application. The Android projects for each speci

7条回答
  •  甜味超标
    2020-12-04 16:11

    Library project is referenced as a raw project dependency (source-based mechanism), not as a compiled jar dependency (compiled-code based library mechanism).

    @yorkw this is not true for the latest versions of ADT Plugin for Eclipse http://developer.android.com/sdk/eclipse-adt.html

    From version 17 Change log

    New build features Added feature to automatically setup JAR dependencies. Any .jar files in the /libs folder are added to the build configuration (similar to how the Ant build system works). Also, .jar files needed by library projects are also automatically added to projects that depend on those library projects. (more info)

    More info http://tools.android.com/recent/dealingwithdependenciesinandroidprojects

    Before that, update overwriting of the Activity from Library project was easy, just exclude the class. Now the library is included as jar file, and there is no way to exclude class file from jar dependency.

    EDIT:

    My solution to overwrete/extend Activity from library jar:

    I created a simple util class:

    public class ActivityUtil {
    
    private static Class getActivityClass(Class clazz) {
    
        // Check for extended activity
        String extClassName = clazz.getName() + "Extended";
        try {
            Class extClass = Class.forName(extClassName);
            return extClass;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            // Extended class is not found return base
            return clazz;
        }
    }
    
    public static Intent createIntent(Context context, Class clazz) {
        Class activityClass = getActivityClass(clazz);
        return new Intent(context, activityClass);
    }
    }
    

    In order to overwrite a library's "SampleActivity" class it a the project which depends on that library, create a new class with the name SampleActivityExtended in the project in the same package and add the new activity to your AndroidManifest.xml.

    IMPORTANT: all intents referencing overwritten activities should be created through the util class in the following manner:

    Intent intent = ActivityUtil.createIntent(MainActivity.this, SampleActivity.class);
    ...
    startActivity(intent);
    

提交回复
热议问题