如何从静态上下文中获取资源内容? [英] How can I get a resource content from a static context?
本文介绍了如何从静态上下文中获取资源内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想先从 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?
推荐答案
- 创建
Application
的子类,例如public class App extends Application {
- 在
AndroidManifest.xml
中设置
标记的android:name
属性以指向您的新类,例如android:name=".App"
- 在您的应用实例的
onCreate()
方法中,将您的上下文(例如this
)保存到名为mContext
的静态字段并创建返回此字段的静态方法,例如getContext()
:
- Create a subclass of
Application
, for instancepublic class App extends Application {
- Set the
android:name
attribute of your<application>
tag in theAndroidManifest.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 namedmContext
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屋!
查看全文