android 通过资源文件名称获取资源文件id
16lz
2021-12-04
1.
- public static Drawable getDrawableByPicName(String picName, Context context) {
- int id = context.getResources().getIdentifier(
- picName == null ? "no_picture" : picName, "drawable",
- GlobalConst.PACKAGE_NAME);
- Drawable p_w_picpath = null;
- if (id <= 0) {
- p_w_picpath = context.getResources().getDrawable(R.drawable.no_picture);
- } else {
- p_w_picpath = context.getResources().getDrawable(id);
- }
- return p_w_picpath;
- }
- 2.
- 可以使用反射,我写了一个小例子。
- public static void main() throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException,
- ClassNotFoundException
- {
- String resourceName = "R.drawable.icon";
- String packageName = "com.bbcode";
- int resourceId = getResourceId(packageName, resourceName);
- if(R.drawable.icon == resourceId){
- //success
- ;
- }
- }
- public static int getResourceId(String packageName, String resourceName)
- throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException,
- ClassNotFoundException
- {
- String[] splitStr = resourceName.split("\\.");
- String classStr = splitStr[0] + "$" + splitStr[1];
- Class c = Class.forName(packageName + "." + classStr);
- Field f = c.getDeclaredField(splitStr[2]);
- return f.getInt(f.getName());
- }
- 3.将图片放到 res/assets 下,不过该方式还没有试过
- public static void main() throws SecurityException, NoSuchFieldException,
更多相关文章
- Android(安卓)5.0以上移动网络开关
- Android(安卓)IDL 小例子
- Android(安卓)线程超时的例子
- android ExpandableListView简单例子
- Android(安卓)长按setOnItemLongClickListener 显示context Menu
- android之sql例子
- android之sql例子
- android 小问题记录
- Android中利用DisplayMetrics取得手机屏幕大小