Android Library Project

▼魔方 西西 提交于 2019-12-18 09:38:42

问题


How can I use an Android Library Project, and overwrite certain classes in the "final project".

In other words, I want to reference a library project, and at the same time, change some of the code..


回答1:


Probably not quite what Android Library projects are all about but you could achieve that by using the interface and class inheritance features of the java language itself.

Library project seem to deal well with merging/overriding resources from the parent in the child and letting you use one codebase with varying app package names.

Given your updated comment about using library projects to have one edition of the app that uses AdMob and one that doesnt, I've revised this answer...

Assuming you dont mind packaging the AdMob library (~138KB) in with your full/paid edition, the simplest thing to do would be to extend an Applcation class and therein declare an enum and a static method to decide whether AdMob ads should be shown.

public class Application extends android.app.Application
{    
    public enum EditionType { LITE, FULL};      
    public static int getAdVisibilityForEdition(Context ctx)
    {
       if (EditionType.valueOf(ctx.getString(R.string.edition)) == EditionType.FULL)
       {
        return View.GONE;
       }
       return View.VISIBLE;
    }
}

You'll add this class to the library project only. In all three of the projects you'll need to add an entry to /res/Strings.xml as such:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="edition">LITE</string>
</resources>

It doesnt matter what the value of this string is in the library project, but you'll vary it in the paid vs. ad supported editions using FULL and LITE respectively.

Finally, to make your activities responsive to these values call something like this in your onCreate() or onResume():

View ad = (View)this.findViewById(R.id.your_adMob_view_id)
ad.setVisibility(Application.getAdVisibilityForEdition
                 (this.getApplicationContext()));

This will work fine with AdMob as the AdMob code wont actually try to get an Ad if the view is not visible.

If you really dont want to have the extra 138K for the AdMob jar and the manifest permissions needed for it in the full edition, there are more elegant ways to do this but would involve using some kind of wrapper around the AdMob stuff and either varying the xml layouts between the editions (to include the AdMob view or not) or inject the AdMob view into the layout programatically.

Hope that helps.



来源:https://stackoverflow.com/questions/5627492/android-library-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!