Android匯出lib時資源id的問題

來源:互聯網
上載者:User

當需要把一個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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.