如何从静态上下文中获取资源内容? [英] How can I get a resource content from a static context?

查看:38
本文介绍了如何从静态上下文中获取资源内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想先从 xml 文件中读取字符串,然后再对小部件执行诸如 setText 之类的任何其他操作,那么如果没有要调用的活动对象,我该怎么做getResources() on?

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?

推荐答案

  1. 创建Application的子类,例如public class App extends Application {
  2. AndroidManifest.xml 中设置 标记的 android:name 属性以指向您的新类,例如android:name=".App"
  3. 在您的应用实例的 onCreate() 方法中,将您的上下文(例如 this)保存到名为 mContext 的静态字段并创建返回此字段的静态方法,例如getContext():
  1. Create a subclass of Application, for instance public class App extends Application {
  2. Set the android:name attribute of your <application> 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 mContext and create a static method that returns this field, e.g. getContext():

它应该是这样的:

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}

现在您可以使用:App.getContext() 每当您想获取上下文时,然后使用 getResources()(或 App.getContext().getResources()).

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

这篇关于如何从静态上下文中获取资源内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆