Android 获取有规律资源Id解决方案
2015-10-04 23:20
543 查看
在多个有规律的资源ID获取的时候,可以使用getIdentifier方法来获取,来获取。
用到场景:工具类打成.jar包的时候,有时候会需要引用到res中的资源,这时候不能将资源一起打包,只能通过反射机制动态的获取资源.
public class Resources int getIdentifier (String name, String defType, String defPackage)
Return a resource identifier for the given resource name.
Parameters
Returns
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)
用到场景:工具类打成.jar包的时候,有时候会需要引用到res中的资源,这时候不能将资源一起打包,只能通过反射机制动态的获取资源.
public class Resources int getIdentifier (String name, String defType, String defPackage)
Return a resource identifier for the given resource name.
param defType:"layout","string","drawable","style","color","array"
Parameters
name | The name of the desired resource. |
---|---|
defType | Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type. |
defPackage | Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package. |
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)
from: http://developer.android.com/reference/android/content/res/Resources.html[/code]
public static int getDrawableId(Context paramContext, String paramString) { return paramContext.getResources().getIdentifier(paramString, "drawable", paramContext.getPackageName()); }
对于这个方法,官方不推荐:
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
更好的解决方案,是参照另外一篇博客的使用反射实现的。
http://www.liaohuqiu.net/cn/posts/android-get-resource-id-by-string/
示例代码:public static int getResId(String variableName, Class<?> c) { try { Field idField = c.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } }
使用:int id = ResourceMan.getResId("icon", R.drawable.class);
这种效率据说比第一种高了4倍。
相关文章推荐
- Android文件写入的实现
- Android基础学习之异步任务使用Handler
- android术语笔记
- Android Studio更新升级方法
- Android动画学习总结---中
- 转自【MDCC技术大咖秀】Android内存优化之OOM
- Android SDK与NDK介绍
- Android--Menu的实现 ActionMode
- Ubuntu配置Android开发环境Android Studio和安装sqliteman
- Android基础学习之AsyncTask(异步任务处理类)二
- android安卓布局总结
- Android项目如何进行签名打包发布
- Android读书笔记------LaunchMode
- android开发学习笔记——用户界面View的五大布局
- Android解决百度地图SDK打包后不能显示地图的方法
- Android Material Design:PopupMenu
- Android:初窥手势识别
- Android Material Design :LinearLayoutCompat添加分割线divider
- Android基础学习之AsyncTask(异步任务处理类)一
- Android开发艺术探索------Bitmap的高效加载