我怎样才能从静态上下文的资源内容? [英] How can I get a resource content from a static context?

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

问题描述

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

解决方案
  1. 创建的子类<一href="http://developer.android.com/reference/android/app/Application.html"><$c$c>Application,例如公共类应用扩展应用{
  2. 安卓:名称属性的&lt;应用&GT; 标记中的 AndroidManifest.xml中来指向新的类,如: 安卓名=应用程序
  3. 在您的应用程序实例的的onCreate()方法,保存环境(例如:)的静态场名为应用并创建一个返回该领域的静态方法,例如: getApp()

这是它应该如何看:

 公共类应用扩展应用{

    私有静态语境mContext;

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

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

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

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. 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 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()).

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

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