Accessing resources from an Android library project?

I am trying to create a library. I have an Android library project and some resources in the res directory that I want to get in the library project code. Android docs say:

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

But I just can't figure out how to do this. Since it is a library and intended for use from other applications, it does not start itself, I do not have an Activity , so I can not use Context to use getResources() . How can I access these resources explicitly without context?

+6
source share
1 answer

Without Activity, it is not possible to use the R class. If you have a test application in your library, the test application will be able to access R, but not from the library itself.

However, you can access resources by name. For example, I have such a class 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 fooobar.com/questions/24999 / ... for more information on ContextWrappers)

And the constructor of the object in the library takes this context wrapper,

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

Then from the application using 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, all of them live inside the library project.

Hope this helps.

0
source

Source: https://habr.com/ru/post/981225/


All Articles