Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 2.2 開發筆記:R.java 與設定檔全解析

編輯:進階開發

在 Android 2.2 的專案裡,有幾個檔案扮演著資源管理與程式設定的核心角色,以下就來逐一拆解。

R.java 檔案

R.java 的內容大致如下:

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon = 0x7f020000;
    }
    public static final class layout {
        public static final int main = 0x7f030000;
    }
    public static final class string {
        public static final int app_name = 0x7f040001;
        public static final int hello = 0x7f040000;
    }
}

從這段程式碼不難看出,每個內部類別的名稱,恰好對應 res 資料夾底下同名稱的子資料夾,而裡頭的每個常數則各自指向一項具體資源。簡單說,R.java 儲存的就是整個專案所有資源的索引,程式透過它便能輕鬆取用各項資源。

AndroidManifest.xml 檔案

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.android.demo"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DemoOne"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

其中,intent-filter 用來描述某個 Activity 在何時、於何地被啟動。每當一個 Activity 要執行某項操作時,它會建立一個 Intent 物件,這個物件能承載諸如「想做什麼事」、「想處理什麼資料」、「資料類型為何」等資訊。Android 會拿這些資訊去比對每個應用程式所對外暴露的 intent-filter,找出最適合的 Activity 來處理呼叫端所指定的資料與操作。

接著看各個主要標籤的含義:

  • manifest:描述整個 package 的所有內容。
  • package:宣告應用程式的套件名稱。
  • application:作為 package 內 application 層級元件宣告的根節點,同時可包含標籤、icon、主題、必要權限等全域屬性。一個 manifest 可以包含零個或一個 application。
  • android:icon:應用程式的圖示。
  • android:label:應用程式的名稱。
  • activity:標記要對應的 Activity,否則程式無法運行,其中可包含一個或多個 intent-filter 來描述該 Activity 所支援的操作。
  • action:元件所支援的 Intent action。
  • category:元件所支援的 Intent category,其中指定應用程式預設啟動的 Activity。
  • uses-sdk:該應用程式所支援的 SDK 版本。

strings.xml 設定檔

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, DemoOne!</string>
    <string name="app_name">DemoOne</string>
</resources>

這份設定檔會與 R.java 中的 string 內部類別一一對應:

public static final class string {
    public static final int app_name = 0x7f040001;
    public static final int hello = 0x7f040000;
}

如何在程式中使用資源

要讀取這些字串資源,可以透過 Resources 物件來取得:

Resources r = this.getContext().getResources();
String appname = ((String) r.getString(R.string.app_name));
String hello = ((String) r.getString(R.string.hello));

透過這樣的機制,字串、圖片、版面等資源都能被集中管理與輕鬆引用,讓整個專案的維護性大幅提升。

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