对非静态字段android进行静态引用

时间:2014-01-14 04:45:04

标签: java android xml static getresource

我尝试开发一个Android应用程序,我需要对非静态变量进行静态(PLACES_API_BASE)引用。请查看以下代码。

private static final String PLACES_API_BASE= getResources().getString(R.string.places_api_base);

但是,我收到错误说明,

Cannot make a static reference to the non-static method getResources() from the type 

是否有任何可能的工作来实现这一目标。请帮忙。谢谢!

4 个答案:

答案 0 :(得分:0)

否则您无法对非静态方法进行静态引用,因为该方法“附加”到“静态”引用(类范围)不“意识到”的实例(对象范围)。

答案 1 :(得分:0)

没办法。 getResources 是一种实例方法。所以你应该在调用它之前创建一个实例。并且 PLACES_API_BASE 是和类常量,它不属于任何实例。

答案 2 :(得分:0)

以下是解决问题的方法:

private final String mPlacesApiBase;

// constructor
public YourClass(Context context) {
    mPlacesApiBase = context.getResources().getString(R.string.places_api_base);

如果您的课程是活动/服务,请将初始化设置为onCreate()

private String mPlacesApiBase;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    mPlacesApiBase = getString(R.string.places_api_base);

我更改了变量名称。根据Java约定,ALL_CAPS_IDENTIFIERS用于在编译时已知的常量,而不是用于动态初始化的事物。前缀m是成员变量的约定。我也删除了static,因为这里似乎没有必要。

答案 3 :(得分:-1)

创建一个对象,然后在方法或构造函数中调用方法getResources()。