Renato Lochetti
Renato Lochetti

Reputation: 4568

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?

Upvotes: 5

Views: 3254

Answers (3)

Guido
Guido

Reputation: 131

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

Upvotes: 7

Dale Wilson
Dale Wilson

Reputation: 9434

Have your main project pass a Context to the library, and call context.getString().

Upvotes: 0

David Manpearl
David Manpearl

Reputation: 12656

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.

Upvotes: 1

Related Questions