Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

把自訂 Android 元件打包成 JAR 的實作方法

編輯:關於 Android 程式設計

在專案開發中,難免會需要自己製作自訂 View 控制項。後續其他專案若也需要,多數人的做法是直接複製貼上——這雖然可行,但並不是好解法。

問題在於,隨著專案數量累積,自訂控制項會越來越多,而這些控制項本質上都是可以重複利用的。與其每次複製,不如把它們封裝成一個 JAR 包並集中維護,之後開發新專案時只需在既有基礎上擴充或直接引用,能省下大量重複勞動。

打包前的工程結構

Android 工程的基本面貌如下:

注意這裡對應的 Activity 檔案已被刪除——因為編譯成 JAR 包時並不需要 Activity。

打包步驟

步驟一:右鍵工程選擇「匯出」

步驟二:匯出目標選擇 java → JAR file

步驟三:取消勾選不必要的檔案

到這一步基本完成,瀏覽並選擇 JAR 的匯出路徑即可。

如何在其他專案中使用

步驟一:新建 lib 資料夾,把 JAR 包放進去。

步驟二:關聯 JAR 包

步驟三:在佈局檔中使用

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:gif="https://schemas.android.com/apk/res/com.terry.jarTest" android:id="@+id/layout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:text="停止" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="開始" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <com.terry.gif.TypegifView android:layout_width="fill_parent" android:id="@+id/gifView1" gif:stop="true" android:layout_height="wrap_content" gif:delay="1"></com.terry.gif.TypegifView> </LinearLayout> 

一個必須注意的坑

如果你的自訂控制項定義了自屬性(例如上例中的 gif:stop 與 gif:delay),那麼 attrs.xml 中的屬性宣告也必須一起複製到使用方的專案裡,否則 XML 解析時會直接報「找不到符號」而無法識別。這是打包成 JAR 相對於打包成 module/AAR 最明顯的不足——資源檔與屬性宣告不會被一起帶走。

若你的控制項用到了自訂屬性或需要打包資源檔,建議改用 AAR 格式,它能完整承載資源、依賴與 ProGuard 設定。

感謝閱讀,希望對大家有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved