是否可以在静态上下文块中获取资源?

ilo*_*mbo 13 resources static android

我想创建一个静态哈希表来将字符串转换为整数.需要注意的是,我想在XML文件中的几个列表中使用我定义为资源的字符串.

我只能使用资源ID写这个:

public class MyActivity extends Activity {

private static Map<Integer, Integer> views = new HashMap<Integer, Integer>();
static {
    views.put(R.string.full_text, MessageTable.VIEW_FULL);
    views.put(R.string.only_text, MessageTable.VIEW_MSG);
    views.put(R.string.tag_text, MessageTable.VIEW_TAGMSG);
}
Run Code Online (Sandbox Code Playgroud)

我没有错误,但我真正需要做的是这样的事情:

public class MyActivity extends Activity {

private static Map<String, Integer> views = new HashMap<String, Integer>();
static {
    views.put(getResources().getString(R.string.full_text), MessageTable.VIEW_FULL);
    views.put(getResources().getString(R.string.only_text), MessageTable.VIEW_MSG);
    views.put(getResources().getString(R.string.tag_text), MessageTable.VIEW_TAGMSG);
}
Run Code Online (Sandbox Code Playgroud)

这给了我在Eclipse中的以下错误:

Cannot make a static reference to the non-static method getResources() from the type ContextWrapper
Run Code Online (Sandbox Code Playgroud)

这个消息很有意义,但没有意义的是资源无法从静态块中访问,人们会认为静态变量是自定义创建的以利用资源.
我想我可以在对象构造函数中填充Hash表,但这意味着要在错误的位置执行它.

zap*_*apl 11

getResources()(〜的缩写MyActivity.this.getResources())需要一个当时未初始化的上下文对象.由于上下文仅在您点击后才可用,您onCreate甚至无法在施工时执行此操作MyActivity.

原因是实例化您的MyActivity类的活动管理器必须在知道必须从xml中提取哪些资源之前确定配置(方向,屏幕大小,语言......). - >资源不是静态的,无法从静态上下文访问.

所以我想我们无法在onCreate以后或之后进行这些操作.

编辑:虽然你当然可以更新静态HashMap(或静态Context)onCreate我不建议你,因为你可以拥有相同Activity的多个实例,可能有不同/不同的配置.存储静态Context也是创建内存泄漏的好方法


Khu*_*zad 7

public Static Resources mResources;
public MyApplication extends Application
{
     @Override
     public void onCreate()
     {
           mResources = getResources();
     }

}
Run Code Online (Sandbox Code Playgroud)

获得对Resources的静态引用后,您可以在整个应用程序的任何位置引用它.但是,我不确定这是否会引入一个妈妈的泄漏;