现在的位置: 首页 > 移动开发 > 正文

android 第三方jar库 反射得到自己的资源ID

2019年09月13日 移动开发 ⁄ 共 2406字 ⁄ 字号 评论关闭

做jar,jar代码获取资源不能直接引用 R.xx.name,

有两种方法:

1.通过方法: int android.content.res.Resources.getIdentifier(String
name,String defType,String
defPackage)

 2.通过反射

第一种方法比较常见,主要看第二种方法:

public class ResoureExchange {
	private static final String TAG = ResoureExchange.class.getName();
	private static ResoureExchange self;

	private Context mContext;

	private static Class<?> CDrawable = null;

	private static Class<?> CLayout = null;

	private static Class<?> CId = null;

	private static Class<?> CAnim = null;

	private static Class<?> CStyle = null;

	private static Class<?> CString = null;

	private static Class<?> CArray = null;

	public static ResoureExchange getInstance(Context context){
		if(self == null){
			self = new ResoureExchange(context);
		}
		return self;
	}

	private ResoureExchange(Context context){
		this.mContext = context.getApplicationContext();
		try{
			CDrawable = Class.forName(this.mContext.getPackageName() + ".R$drawable");
			CLayout = Class.forName(this.mContext.getPackageName() + ".R$layout");
			CId = Class.forName(this.mContext.getPackageName() + ".R$id");
			CAnim = Class.forName(this.mContext.getPackageName() + ".R$anim");
			CStyle = Class.forName(this.mContext.getPackageName() + ".R$style");
			CString = Class.forName(this.mContext.getPackageName() + ".R$string");
			CArray = Class.forName(this.mContext.getPackageName() + ".R$array");

		}catch(ClassNotFoundException e){
			Log.i(TAG,e.getMessage());
		}
	}

	public int getDrawableId(String resName){
		return getResId(CDrawable,resName);
	}
	
	public int getLayoutId(String resName){
		return getResId(CLayout,resName);
	}
	
	public int getIdId(String resName){
		return getResId(CId,resName);
	}
	
	public int getAnimId(String resName){
		return getResId(CAnim,resName);
	}
	
	public int getStyleId(String resName){
		return getResId(CStyle,resName);
	}
	
	public int getStringId(String resName){
		return getResId(CString,resName);
	}
	
	public int getArrayId(String resName){
		return getResId(CArray,resName);
	}
	
	private int getResId(Class<?> resClass,String resName){
		if(resClass == null){
			Log.i(TAG,"getRes(null," + resName + ")");
			throw new IllegalArgumentException("ResClass is not initialized. Please make sure you have added neccessary resources. Also make sure you have " + this.mContext.getPackageName() + ".R$* configured in obfuscation. field=" + resName);
		}

		try {
			Field field = resClass.getField(resName);
			return field.getInt(resName);
		} catch (Exception e) {
			Log.i(TAG, "getRes(" + resClass.getName() + ", " + resName + ")");
			Log.i(TAG, "Error getting resource. Make sure you have copied all resources (res/) from SDK to your project. ");

			Log.i(TAG, e.getMessage());
		} 

		return -1;
	}
}

直接看代码,一目了然。[来源于反编译友盟统计jar]

原文作者:H-G-Y

原文地址:http://blog.csdn.net/go_to_learn/article/details/9410727

抱歉!评论已关闭.