Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing resources from Android library project?

I am trying to build a library. I have an Android library project and some resources under the res directory that I want to access in the library project's code. The Android docs says:

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

But I just can't figure out how to do this. Because it's a library and intended to be used from other applications, not run itself, I have no Activity, so I can't get a Context to use getResources(). How can I access these resources explicitly without a context?

like image 301
sqshemet Avatar asked Jan 19 '15 16:01

sqshemet


People also ask

How do I access library on Android?

To find your Library, go to the bottom menu bar and select Library .

What are the resources in Android?

Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more. You should always externalize app resources such as images and strings from your code, so that you can maintain them independently.


1 Answers

Without an Activity, it doesn't seem possible to use the R class. If you have a test application within your library, the test application will be able to access R, but not from the lib itself.

Still, you can access the resources by name. For instance, I have a class like this inside my library,

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;
  }
}

(See https://stackoverflow.com/a/24972256/1765629 for more information about ContextWrappers)

And the constructor of an object in the library takes that context wrapper,

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

Then, from the app that uses the lib, I have to pass the context,

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

MyContext, MyLibClass, and a_file_inside_my_lib_res, they all live inside the library project.

I hope it helps.

like image 138
endavid Avatar answered Oct 21 '22 06:10

endavid