资源文件中的最终变量 [英] Final variable from resources file

查看:74
本文介绍了资源文件中的最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 final 变量的活动.我将它们的值(假设它们都是字符串)提取到资源文件中.

I have an activity with some final variables. I extracted their values (let's assume they're all Strings) into a resources file.

问题:

如果我直接在实例上分配它们(如下所示):

If I directly assign them on the instantiation (as following):

私有最终字符串PREFERENCE_NAME = getResources().getString(R.string.preference_name);

我收到以下错误:

原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'

我了解问题所在;onCreate()方法尚未被调用,这意味着我无法访问上下文相关的方法( getResources()).

I understand the problem; the onCreate() method has not been called yet which means I cannot access context-related methods (getResources()).

如果我想在活动的onCreate()方法中分配值,则会收到错误无法为最终变量"PREFERENCE_NAME"分配值

If I want to assign the value in the onCreate() method of the activity, I get the error Cannot assign value to final variable 'PREFERENCE_NAME'

问题是:如何从资源文件中分配最终变量?如果这不可能,那么解决方案的最佳实践是什么?

The question is: How can I get my final variables to be assigned from the resources file? And if this is not possible, what is the best practice for a solution?

谢谢.

推荐答案

在这种情况下,我认为最好的方法是对资源进行多次调用.您仍然只需要在一个位置更改该值,并且对 getResources()的调用并不昂贵.

In this case I think the best thing to do it just make multiple calls to the resources. You still only have to change the value in one place and the call to getResources() isn't an expensive one.

这篇关于资源文件中的最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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