如何获取AssetManager没有提及语境?语境、AssetManager

2023-09-04 23:20:23 作者:凉心姑娘百毒不侵

我有需要获得它的一个引用类的应用程序的 AssetManager 。此类不扩展任何种类的Andr​​oid UI类,因此它不具有的getContext()的方法,或者类似的话。是否有某种静态 Context.getCurrentApplicationContext()类型的方法?

要澄清:我的类拟用于像库,对于其他的应用程序。它没有相关的的Andr​​oidManifest.xml 或在其上调用它的上下文控制。

解决方案 创建的子类Application,例如公共类应用扩展应用{安卓:名称属性的<应用> 标记中的 AndroidManifest.xml中来指向新的类,如: 安卓名=应用程序 在您的应用程序实例的的onCreate()方法,保存环境(例如:)的静态场名为应用并创建一个返回该领域的静态方法,例如: getApp()

这是它应该如何看:

 公共类应用扩展应用{

    私有静态语境mContext;

    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        mContext =这一点;
    }

    公共静态上下文的getContext(){
        返回mContext;
    }
}
 
一个Linux小白体验友善之臂品牌知名老板子的摸爬滚打历程

现在,您可以使用: App.getContext()时,你希望得到一个上下文,然后 getAssetManager()(或 App.getContext()。getAssetManager())。

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 have a getContext() method, or anything similar. Is there some sort of static Context.getCurrentApplicationContext() type of method?

To clarify: my class is intended to be used like a library, for other applications. It has no associated AndroidManifest.xml or control over the context which is calling it.

解决方案

Create a subclass of Application, for instance public class App extends Application { Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App" 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()).