我想从 XML
文件之前,我做很多别的事情,比如的setText
上的小部件读取字符串,所以我该怎么办,没有一个活动对象调用 getResources()
吗?
公共类应用扩展应用{
将安卓:名称
属性的<应用>
标记中的 AndroidManifest.xml中
来指向新的类,如: 安卓名=应用程序
在您的应用程序实例的的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?
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()
).