How to obtain AssetManager without reference to Context?

后端 未结 2 498
不思量自难忘°
不思量自难忘° 2020-12-13 20:31

I have a class that needs to obtain a reference to it\'s application\'s AssetManager. This class does not extend any sort of android UI class, so it doesn\'t h

2条回答
  •  猫巷女王i
    2020-12-13 20:59

    1. Create a subclass of Application, for instance public class App extends Application {
    2. Set the android:name attribute of your tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
    3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():

    This is how it should look:

    public class App extends Application{
    
        private static Context mContext;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mContext = this;
        }
    
        public static Context getContext(){
            return mContext;
        }
    }
    

    Now you can use: App.getContext() whenever you want to get a context, and then getAssetManager() (or App.getContext().getAssetManager()).

提交回复
热议问题