Here is the situation: I Have two projects. Let's say a LibraryProject
and a MainProject
. The MainProject
references the LibraryProject
as a library.
I have one activity in the LibraryProject
that needs to discover if the MainProject
have defined a specific drawable, let's say "logo.png" (Think that the logo image must be defined by each `MainProject, and not by the LibraryProject.
How to, in one activity of the LibraryProject
, discover if the MainProject
has this image in the res/drawable
folder?
Obviouslly I have tried to see if R.drawable.logo != 0
(or variation of it), but as you know, this line will not compile, since the image is not in the res/drawable
folder of the LibraryProject
.
I also tried getResources().getIdentifier("logo", "drawable", null) != 0
but this boolean expression is always returning false, since the .getIdentifier()
always returns zero.
Any idea?
You can try this: (but remember, the context is always "ChildProject")
public static Drawable getDrawable(Context context, String resource_name){
try{
int resId = context.getResources().getIdentifier(resource_name, "drawable", context.getPackageName());
if(resId != 0){
return context.getResources().getDrawable(resId);
}
}catch(Exception e){
Log.e(TAG,"getDrawable - resource_name: "+resource_name);
e.printStackTrace();
}
return null;
}
You need to provide a default resource in the Library Project. If there is an identically named resource in your MainProject
, it will override the Library Project resource.
For example, if you provide "res/drawable/logo.png" in both projects, then R.drawable.logo
in the Library Project will use the "logo.png" image that is in the "res/drawable" folder of the MainProject.
This answer does not address how the Library Project should discover if the Main Project has a resource, only how to force use of it, if there is one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With