1

I have created an Android library project that i am linking with my Android app. In the drawable folder of the library project, I have added a few images. Now I am trying to access these images from a non-activity class in the same project but they are not being accessed when I try to access them using the following snippet

Drawable drawable=context.getResources().getDrawable(R.drawable.image);

The import of R file is correct and the image id is being generated correctly in the R file. The context is correct. I tried refreshing and cleaning/building the project multiple times but nothing seems to work.

Help!

Merlevede
  • 8,140
  • 1
  • 24
  • 39
dexter
  • 41
  • 1
  • 1
  • 7

2 Answers2

0

[Note: Answer copied from here.]

Yes you can if you know the package name of your library.
Resources.getIdentifier(...)

You can do:

getResources().getIdentifier("res_name", "res_type", "com.library.package");

ex:

R.id.settings would be:

getResources().getIdentifier("settings", "id", "com.library.package");

Community
  • 1
  • 1
Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • This returns an id. I need a drawable. How do I make the conversion? And why exactly is this happening anyway? – dexter Oct 26 '16 at 18:20
  • The identifier is the one you use instead of `R.drawable.image` in your original code. – Merlevede Oct 26 '16 at 18:24
  • R.drawable.image gives me a drawable, this gives me an integer! – dexter Oct 26 '16 at 18:26
  • False!!! R.drawable.image gives you an integer!!! Look at the documentation [here](https://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int,%20android.content.res.Resources.Theme)). `R.drawable.image` retruns the identifier of the image, and the `getDrawable()` function gets the Drawable from the identifier – Merlevede Oct 26 '16 at 19:36
0

I'm not sure I understand the quest completely (the problem you are having is that the method does not return a drawable?

I'm not sure you about how you are getting the context, but you could try this:

Drawable drawable = ContextCompat(getContext(), R.drawable.image);

If you are storing the context in a variable, you can pass the variable instead of using getContext().

Additionally, the method you are using to get the drawable is deprected, so you shouldn't be using it anymore.

Let me know if it helped you and remember to upvote/select this as correct answer if it did, cheers.

FabioR
  • 696
  • 9
  • 18