从Android库项目访问资源?

我正在尝试建立一个图书馆.我有一个 Android库项目和res目录下的一些资源,我想在库项目的代码中访问它. Android文档说:

source code in the library module can access its own resources through its R class

但我无法弄清楚如何做到这一点.因为它是一个库,打算从其他应用程序中使用,而不是自己运行,所以我没有Activity,所以我无法使用getResources()来获取Context.如何在没有上下文的情况下显式访问这些资源?

解决方法

没有Activity,似乎不可能使用R类.如果您的库中有测试应用程序,测试应用程序将能够访问R,但不能访问lib本身.

您仍然可以按名称访问资源.
例如,我的库中有一个这样的类,

public class MyContext extends ContextWrapper {
  public MyContext(Context base) {
    super(base);
  }

  public int getResourceId(String resourceName) {
    try{
        // I only access resources inside the "raw" folder
        int resId = getResources().getIdentifier(resourceName,"raw",getPackageName());
        return resId;
    } catch(Exception e){
        Log.e("MyContext","getResourceId: " + resourceName);
        e.printStackTrace();
    }
    return 0;
  }
}

(有关ContextWrappers的更多信息,请参阅https://stackoverflow.com/a/24972256/1765629)

并且库中对象的构造函数采用该上下文包装器,

public class MyLibClass {
  public MyLibClass(MyContext context) {
    int resId = context.getResourceId("a_file_inside_my_lib_res");
  }
}

然后,从使用lib的应用程序,我必须传递上下文,

public class MyActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    MyLibClass a = new MyLibClass(new MyContext(this));
  }
}

MyContext,MyLibClass和a_file_inside_my_lib_res,它们都存在于库项目中.

我希望它有所帮助.

相关文章

文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...
文章浏览阅读8.9w次,点赞4次,收藏43次。前言:在Android上...
文章浏览阅读1.1w次,点赞4次,收藏17次。Android Studio提供...