當需要把一個Android匯出為jar包時,如果裡面有用到Resource,比如R.layout,R.id 其它程式引入這個包的時候會遇到id找不到的情況。
這是因為匯出jar的時候裡面的R.id已經替換為一個int常量,而在新的程式中resource id會重建,兩者不匹配就會產生問題。
所以在這個Android工程中不能使用import com.xx.R,否則會出現問題,必須在用到資源的時候用另外一個函數去擷取它的真正id.
解決辦法大致就是利用java的反射機制,通過string來找到類,從而找到變數值。
方法一
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