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

Android 應用資源完全指南:字串、顏色、尺寸、陣列、布林與整數

編輯:關於 Android 程式設計

一、Android 資源的分類

Android 中的資源分為兩大類:可直接存取的資源,以及無法直接存取的原始資源。

直接存取資源:透過 R 類存取,皆存放於 res 目錄下。編譯時會自動產生 R.java 資源索引檔。

原始資源:存放於 assets 下,無法用 R 類存取,只能透過 AssetManager 以二進位串流形式讀取。

二、res 目錄結構詳解

· res/animator:屬性動畫的 XML 檔目錄。屬性動畫需完整定義起止值、動作與重複次數等參數。
· res/anim:補間動畫的 XML 檔目錄。補間動畫只定義起始與結束影格,中間過程由系統計算。
· res/color:顏色列表的 XML 檔目錄。
· res/drawable:存放真實的點陣圖檔,也可存放 Drawable 物件及子類別的 XML 檔。
· res/layout:介面版面配置檔目錄。
· res/menu:選單檔目錄,可應用於選項選單、子選單與情境選單。
· res/raw:存放原始資源,作用與 assets 相同,可透過 openRawResource(int) 取得二進位輸入流。
· res/values:存放字串、整數、顏色、陣列等資訊的 XML 檔目錄,根元素為 resource。
· res/xml:原生 XML 檔,可用 Resource.getXML() 存取。

三、values 目錄中的子標籤

· string:代表一個字串。
· integer:代表一個整數值。
· bool:代表一個 boolean 值。
· color:代表一個顏色值。
· array:代表一般陣列。
· string-array:代表字串陣列。
· integer-array:代表 int 陣列。
· style:代表樣式。
· dimen:代表一個尺寸。

四、分類檔案的好處

若把所有資源塞進同一個 XML,維護難度會隨專案膨脹而快速上升。實務上建議按類型拆分:

· arrays.xml:陣列資源
· colors.xml:顏色資源
· dimens.xml:尺寸值資源
· strings.xml:字串資源
· styles.xml:樣式資源

五、Java 程式碼中的資源存取

透過 R 類存取的語法:

[packageName.]R.resourceType.resourceName

· packageName:R 類所在的套件名,用於限定類型。R 類可能來自兩處,一是程式本身的清單檔,一是 Android 系統。
· resourceType:R 類中代表資源類型的名稱,例如 R.string 為字串資源、R.integer 為整數資源。
· resourceName:資源名稱,對應類型子標籤的 name 屬性值。

Resource 類是 Android 的資源存取控制類,提供大量取得實際資源的方法,可透過 Context.getResources() 取得:

// 獲取 Resource 資源,這個方法在 Activity 中執行
Resources resources = getResources();
// 獲取字符串資源
String hello = resources.getString(R.string.hello_world);
// 獲取圖片資源
Drawable luncher = resources.getDrawable(R.drawable.ic_launcher);

若要讀取原始資源,則用 resources.getAssets() 取得 AssetManager 物件。

六、XML 中的資源參照

@[packageName:]resourceType/resourceName

· packageName:資源類型所在的套件。若被參照的資源與本 XML 在同一套件下,可省略。
· resourceType:資源類型,如 layout、drawable、string 等。
· resourceName:資源所在的 XML 中元素的 android:name 屬性值,或無副檔名的檔名(圖片、版面檔等)。

七、幾種資源的位置與參照方式

字串資源:/res/values/strings.xml,參照方式 R.string.xxx
顏色資源:/res/values/colors.xml,參照方式 R.color.xxx
尺寸資源:/res/values/dimens.xml,參照方式 R.dimens.xxx

顏色定義方式補充:白光是紅、綠、藍三色光的合成;三者皆為最大值時呈白色,三者相等但非最大值時呈灰色,其中一或兩色較高則產生各種彩色。顏色由 alpha(透明度)與 red、green、blue 共同表示,值總是以 # 開頭;若省略 alpha,預設完全不透明。四種寫法如下:

· #RGB:三原色,每值 16 級,範圍 0~f。
· #ARGB:透明度加三原色,每值 16 級。
· #RRGGBB:三原色,每值 256 級,範圍 0~ff。
· #AARRGGBB:透明度加三原色,每值 256 級。

八、各類型資源的定義檔

字串資源(/res/values,根元素 resource,子元素 string,name 屬性指定變數名,標籤文本即字串內容):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ResourceTest</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
</resources>

顏色資源(根元素 resource,子元素 color):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="red">#FF4000</color>
    <color name="black">#120A2A</color>
    <color name="green">#00FF00</color>
    <color name="yellow">#FFFF00</color>
</resources>

尺寸資源(根元素 resource,子元素 dimen):

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

九、陣列資源

通常定義在 /res/values/arrays.xml,根標籤為 resources,子標籤依型別分為 array、string-array 與 integer-array。

XML 中參照:@[packageName:]array/arrayName
Java 中參照:[packageName.]R.array.arrayName

取得實際陣列的方法有三:

· TypedArray obtainTypedArray(int id):取得一般陣列,再用 getXxx(int index) 依索引取值;
· String[] getStringArray(int id):取得字串陣列;
· int[] getIntArray(int id):取得整數陣列。

十、綜合示例

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="c1">#F00</color>
    <color name="c2">#0F0</color>
    <color name="c3">#00F</color>
    <color name="c4">#0FF</color>
    <color name="c5">#F0F</color>
    <color name="c6">#FF0</color>
    <color name="c7">#07F</color>
    <color name="c8">#70F</color>
    <color name="c9">#F70</color>
</resources>

dimens.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="spacing">8dp</dimen>
    <dimen name="cell_width">60dp</dimen>
    <dimen name="cell_height">66dp</dimen>
    <dimen name="title_font_size">18sp</dimen>
</resources>

strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ValuesResTest!</string>
    <string name="app_name">字符串,數字,尺寸,數組資源</string>
    <string name="c1">F00</string>
    <string name="c2">0F0</string>
    <string name="c3">00F</string>
    <string name="c4">0FF</string>
    <string name="c5">F0F</string>
    <string name="c6">FF0</string>
    <string name="c7">07F</string>
    <string name="c8">70F</string>
    <string name="c9">F70</string>
</resources>

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="plain_arr">
        <item>@color/c1</item>
        <item>@color/c2</item>
        <item>@color/c3</item>
        <item>@color/c4</item>
        <item>@color/c5</item>
        <item>@color/c6</item>
        <item>@color/c7</item>
        <item>@color/c8</item>
        <item>@color/c9</item>
    </array>
    <string-array name="string_arr">
        <item>@string/c1</item>
        <item>@string/c2</item>
        <item>@string/c3</item>
        <item>@string/c4</item>
        <item>@string/c5</item>
        <item>@string/c6</item>
        <item>@string/c7</item>
        <item>@string/c8</item>
        <item>@string/c9</item>
    </string-array>
    <string-array name="books">
        <item>Java</item>
        <item>Ajax</item>
        <item>Android</item>
    </string-array>
</resources>

主介面版面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:gravity="center"
        android:textSize="@dimen/title_font_size" />
    <GridView
        android:id="@+id/grid01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:horizontalSpacing="@dimen/spacing"
        android:verticalSpacing="@dimen/spacing"
        android:numColumns="3"
        android:gravity="center">
    </GridView>
    <ListView
        android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/books" >
    </ListView>
</LinearLayout>

Activity:

package WangLi.Resources.Values;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class ValuesResTest extends Activity {
    /** Called when the activity is first created. */
    String[] texts;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        texts = getResources().getStringArray(R.array.string_arr);
        // 創建一個 BaseAdapter 對象
        BaseAdapter ba = new BaseAdapter() {
            public int getCount() {
                return texts.length;
            }
            public Object getItem(int position) {
                return texts[position];
            }
            public long getItemId(int position) {
                return position;
            }
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView text = new TextView(ValuesResTest.this);
                Resources res = ValuesResTest.this.getResources();
                // 使用尺寸資源來設置文本框的高度、寬度
                text.setWidth((int) res.getDimension(R.dimen.cell_width));
                text.setHeight((int) res.getDimension(R.dimen.cell_height));
                // 使用字符串資源設置文本框的內容
                text.setText(texts[position]);
                TypedArray icons = res.obtainTypedArray(R.array.plain_arr);
                // 使用顏色資源來設置文本框的背景色
                text.setBackgroundDrawable(icons.getDrawable(position));
                text.setTextSize(20);
                return text;
            }
        };
        GridView grid = (GridView) findViewById(R.id.grid01);
        grid.setAdapter(ba);
    }
}

十一、布林與整數資源

整數資源,/res/values/integer.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="size_1">10</integer>
    <integer name="size_2">20</integer>
</resources>
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 獲取 Resource 資源,這個方法在 Activity 中執行
        Resources resources = getResources();
        int size_1 = resources.getInteger(R.integer.size_1);
        System.out.println(size_1);
    }
}

布林資源,/res/values/bool.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_true">true</bool>
    <bool name="is_false">false</bool>
</resources>
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 獲取 Resource 資源,這個方法在 Activity 中執行
        Resources resources = getResources();
        boolean is_true = resources.getBoolean(R.bool.is_true);
        System.out.println(is_true);
    }
}

把這些值抽到資源檔而不是寫死在程式碼裡,除了便於集中管理,更是多語系與多裝置自適應的基礎——同一份程式碼,換一套 values 目錄就能換一個樣貌。

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