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

Here is the situation: I have two projects. Let a LibraryProjectand a say MainProject. MainProjectrefers to LibraryProjectboth the library.

I have one action in LibraryProjectthat should detect if I have MainProjectdefined a specific output method, say, "logo.png" (think that the logo image should be determined by each "MainProject", and not by the library project.

How in one of the actions to LibraryProjectfind out if MainProjectthis image is in the folder res/drawable?

Obviously, I tried to find out if there is R.drawable.logo != 0(or its change), but, as you know, this line will not compile, since the image is not in the folder res/drawable LibraryProject.

I also tried getResources().getIdentifier("logo", "drawable", null) != 0, but this boolean expression always returns false, since it .getIdentifier()always returns zero.

Any idea?

+5
source share
3 answers

You can try the following: (but remember that 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;
}
+5
source

You need to provide the default resource in the library project. If yours MainProjecthas an identically named resource, it will override the library project resource.

For example, if you provide "res / drawable / logo.png" in both projects, then R.drawable.logothe library project will use the image "logo.png" located in the "res / drawable" folder of the Main project.


, , , , .

0

Ask your main project to pass the context to the library and call context.getString ().

0
source

All Articles