自定義工具類-----通過圖片名稱獲取資原始檔(運用反射)
阿新 • • 發佈:2019-01-11
一、用kotlin寫的話如下: object ReflectUtil { /** * 獲取圖片名稱獲取圖片的資源id的方法 ,呼叫的時候 * getResourceByReflect("sdf", R.mipmap::class.java) */ fun getResourceByReflect(imageName: String, mipmap: Class<*>): Int { // val mipmaps = mipmap var field: Field? = null var r_id = 0 try { field = mipmap.getField(imageName) field!!.isAccessible = true r_id = field.getInt(field.name) } catch (e: Exception) { Log.e("ERROR", "PICTURE NOT FOUND!") } return r_id } /** * 獲取圖片名稱獲取圖片的drawable id的方法 * getDrawableByReflect("sdf", R.mipmap::class.java) */ fun getDrawableByReflect(imageName: String,drawable : Class<*>): Int { // val drawables = drawable var field: Field? = null var r_id = 0 try { field = drawable.getField(imageName) field!!.isAccessible = true r_id = field.getInt(field.name) } catch (e: Exception) { Log.e("ERROR", "PICTURE NOT FOUND!") } return r_id } }
二、用java寫的話如下:
public class ReflectUtils { /** * 獲取圖片名稱獲取圖片的資源id的方法 * @return */ public static int getResourceByReflect(String imageName, Class mipmap) { // Class mipmap = R.mipmap.class; // Class mipmaps = mipmap; Field field = null; int r_id = 0; try { field = mipmap.getField(imageName); field.setAccessible(true); r_id = field.getInt(field.getName()); } catch (Exception e) { Log.e("ERROR", "PICTURE NOT FOUND!"); } return r_id; } /** * 獲取圖片名稱獲取圖片的drawable id的方法 */ public static int getDrawableByReflect(String imageName, Class drawable) { // Class drawable = R.drawable.class; Field field = null; int r_id = 0; try { field = drawable.getField(imageName); field.setAccessible(true); r_id = field.getInt(field.getName()); } catch (Exception e) { Log.e("ERROR", "PICTURE NOT FOUND!"); } return r_id; } }