Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Resource from a project inside a library project

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?

like image 794
Renato Lochetti Avatar asked Mar 27 '13 17:03

Renato Lochetti


2 Answers

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;
}
like image 192
Guido Avatar answered Nov 15 '22 03:11

Guido


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.

like image 34
David Manpearl Avatar answered Nov 15 '22 05:11

David Manpearl