简体   繁体   中英

Accessing drawable rescources from a library project in Android

I am trying to search for drawable (pictures) in a resource file in android from my library project Is it possible without the context of the of the actual android project or do I need to add that in? Also how would I be able to find an ID through my library project by using a string as the name of the ID and then convert it to the appropriate integer to set the background resource.

This is what I have tried so far: This works but only looks at the rescources in the library project, I need to look at the resources in the current application project

  try
            {
                Class res = R.drawable.class;
                Field field =
                    res.getField("string_ID_I_want");
                drawableId = field.getInt(null);
            }

The actual drawable resources are compiled into your app, so accessing them is no different than accessing normal app resources.

Supposing the ID of the drawable in the library is big_picture. Then R.drawable.big_picture is the ID of the drawable you want to load. You don't have to use introspection. If R.drawable.big_picture is not available, there's something wrong with your project setup (or a compile error).

What's the package name of your library project.

If your package name is com.examplelib.blahblah and your drawable is called myicon , just make sure to

import com.examplelib.blablah.R;

Then in the same file where you imported this R, you can just type R.drawable.myicon

Context context = getApplicationContext();
Resources r = context.getResources();
r.getDrawable(id);  //pass your drawable id in it, could be R.id.whatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM