简体   繁体   English

从Android中的库项目访问可绘制的资源

[英]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? 我正在尝试从我的图书馆项目中搜索android中资源文件中的drawable(图片),是否可能没有实际android项目的上下文,或者是否需要添加? 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. 另外,如何通过使用字符串作为ID名称通过我的图书馆项目找到ID,然后将其转换为适当的整数以设置背景资源。

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. 假设库中可绘制的ID为big_picture。 Then R.drawable.big_picture is the ID of the drawable you want to load. 然后R.drawable.big_picture是要加载的可绘制对象的ID。 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). 如果R.drawable.big_picture不可用,则您的项目设置有问题(或编译错误)。

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 如果您的软件包名称为com.examplelib.blahblah而您的可绘制对象称为myicon ,则只需确保

import com.examplelib.blablah.R;

Then in the same file where you imported this R, you can just type R.drawable.myicon 然后,在导入此R的同一文件中,只需键入R.drawable.myicon

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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