我怎样才能从静态上下文的资源内容?上下文、静态、内容、资源

2023-09-11 12:25:01 作者:闹够了就滚

我想从 XML 文件之前,我做很多别的事情,比如的setText 上的小部件读取字符串,所以我该怎么办,没有一个活动对象调用 getResources()吗?

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

这是它应该如何看:

 公共类应用扩展应用{

    私有静态语境mContext;

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

    公共静态上下文的getContext(){
        返回mContext;
    }
}
 

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

java关于资源销毁的事,你的项目应该如何正确分层

I want to read strings from an xml file before I do much of anything else like setText on widgets, so how can I do that without an activity object to call getResources() on?

解决方案

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 getResources() (or App.getContext().getResources()).