我想创建一个静态 哈希表来将字符串 转换为整数。这里需要注意的是,我想在 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);
}
我没有收到任何错误,但我真正需要做的是这样的:
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);
}
这让我在 Eclipse 中出现以下错误:
Cannot make a static reference to the non-static method getResources() from the type ContextWrapper
该消息是有道理的,但没有意义的是静态 block 无法访问资源,人们会认为静态变量是为使用资源而自定义创建的。
我想我可以在对象构造函数期间填充哈希表,但这意味着在错误的地方进行。
最佳答案
getResources()
(~ MyActivity.this.getResources()
的缩写)需要一个当时未初始化的上下文对象。由于上下文仅在您点击 onCreate
后可用,您甚至无法在 MyActivity
的构造时执行此操作。
原因是实例化您的 MyActivity
类的 Activity 管理器在知道必须从xml。 -> 资源不是静态的,不能从静态上下文访问。
所以我想没有办法在 onCreate
或更高版本中执行这些操作。
编辑:虽然您当然可以从 onCreate
更新静态 HashMap(或静态 Context
),但我不建议这样做,因为您可以有多个相同的实例可能具有不同/更改配置的 Activity 。存储静态 Context
也是创建 Memory Leak 的好方法
关于android - 是否可以在静态上下文 block 中获取资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195417/