打第三方jar包,找不到资源文件问题解决方案

时间:2021-04-24 04:32:50

这段时间做的一个项目,要把项目打成jar包,提供给别人使用,但当在另外一个i项目中导入sdk时,发现资源文件找不到,郁闷老久,终于解决了,记录一下

当需要把一个Android的导出为JAR包时,如果里面有用到资源,比如R.layout,R.id其它程序引入这个包的时候会遇到ID找不到的情况。

ID会重新生成,两者不匹配就会产生问题。

所以在这个Android的工程中不能使用

方法一

public static int getId(Context paramContext, String paramString1, String paramString2)
{
try
{
Class localClass = Class.forName(paramContext.getPackageName() + ".R$" + paramString1);
Field localField = localClass.getField(paramString2);
int i = Integer.parseInt(localField.get(localField.getName()).toString());
return i;
} catch (Exception localException)
{
Log.e("getIdByReflection error", localException.getMessage());
}
 
return 0;
}

方法二

这个也是替换Theme的方法

   public static int getLayoutResIDByName(Context context, String name) {
return context.getResources().getIdentifier(name, "layout",
context.getPackageName());
}
 
public static int getIdResIDByName(Context context, String name) {
return context.getResources().getIdentifier(name, "id",
context.getPackageName());
}
 
public static int getStringResIDByName(Context context, String name) {
return context.getResources().getIdentifier(name, "string",
context.getPackageName());
}
 
public static int getDrawableResIDByName(Context context, String name) {
return context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
}
 
public static int getRawResIDByName(Context context, String name) {
return context.getResources().getIdentifier(name, "raw",
context.getPackageName());
}

方法三

Android工程间相互依赖,只适用于在Eclipse中开发

参考官方说明 http://developer.android.com/guide/developing/projects/projects-eclipse.html