【问题标题】:How to access resource file from class which is not extending Activity in Android?如何从未在 Android 中扩展 Activity 的类访问资源文件?
【发布时间】:2011-10-22 03:24:50
【问题描述】:

我有一个类,在构造函数中传递了上下文

public abstract class AbstractDbAdapter {
    protected Context context; 

    public AbstractDbAdapter(Context context) {
        this.context = context;     
        String email = context.getString(R.string.my_email);
    }

最后一个字符串的错误没有编译:

package R does not exist context.getString(R.string.my_email);

包 R 绝对存在!我使用相同的调用:

context.getString(R.string.my_email);

在其他扩展 Activity 的类中没有任何问题。此外,我看到了字符串:

public static final class string {
    ...
    public static final int my_email=0x7f06001e;
    ...
}

在 R.java 中。我应该怎么做才能让我的代码在不扩展 Activity 的类中工作!?

【问题讨论】:

标签: android android-activity constructor resources android-context


【解决方案1】:

您的活动和 AbstractDbAdapter 必须位于不同的包中。

您只需要导入R 类。

import com.example.R;

【讨论】:

  • 你是对的!非常感谢!但是 Netbeans 编译器总是要求我在这种情况之前添加所需的导入......
  • 是的,Android资源有点奇怪; ...R 包是从资源动态构建的,这并不真正符合 Java 包的传统 IDE 概念。
猜你喜欢
  • 2014-11-05
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
相关资源
最近更新 更多