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

Android 應用資源全解析:從 res 目錄到 StateListDrawable 與 AnimationDrawable

編輯:關於 Android 程式設計

Java 初學者常把 "hello"、123 這類字面值直接寫進程式碼,過一陣子回頭看,往往已經想不起來當初為什麼這樣定義。有經驗的人會改用常數,例如 ResultSet.TYPE_FORWARD_ONLY,一眼就知道意義所在,耦合度也隨之降低。

Android 把這個思路再往前推一步:把字串、顏色、數組、菜單等資源集中放到 res 目錄統一管理,程式碼與 XML 直接引用這些資源的 id,而不是複製貼上內容。

資源的分類與存放

Android 的應用資源大體分成兩類:

1. 無法透過 R 類訪問的原生資源,放在 assets 目錄下
2. 可透過 R 資源清單類訪問的資源,放在 res 目錄下

res 之下的常用子目錄:

  • /res/animator:屬性動畫的 XML 檔
  • /res/anim:補間動畫(tween animation)的 XML 檔
  • /res/color:颜色狀態列表 XML
  • /res/drawable:點圖(png、jpg、gif)與各種 Drawable 物件(BitmapDrawable、NinePatchDrawable、StateListDrawable、AnimationDrawable、ShapeDrawable 等)
  • /res/layout:使用者介面布局檔
  • /res/menu:選項菜單、子菜單、上下文菜單
  • /res/raw:任意原生資源(音訊、影片等),以 Resources.openRawResource(int id) 取得二進位輸入流
  • /res/values:字串、數組、整數、顏色等簡單值,全部收在 <resources> 節點下,建議不同類型分檔存放

在 Java 與 XML 中引用資源

Java 程式碼中的寫法:

<package_name>.R.<resource_type>.<resource_name>

例如 android.R.layout.simple_expandable_list_item_1,其中包名可以省略。

要注意的是,這種寫法拿到的並不是資源物件本身,而是一個 int 型別的資源清單項。Android 的 API 允許直接用這個 int 代表資源,真正要取出實體,得靠 Resources 這個「資源總管家」。它主要提供兩類方法:

getXxx(int id):依資源 id 取得實際資源
getAssets():取得可訪問 /assets/ 的 AssetManager 物件

Resources 由 Context 呼叫 getResources() 取得:

Resources res = getResources();
String mainTitle = res.getText(R.string.main_title);      // 字串
Drawable icon   = res.getDrawable(R.drawable.ic_launcher); // 圖片
int[] arr       = res.getIntArray(R.array.books);          // 數組

在 XML 中先定義,再由控件引用:

<resources>
    <color name="red">#ff0000</color>
    <string name="hello">Hello</string>
</resources>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/red" />

數組資源同理,而且資源之間可以互相引用:

<resources>
    <string-array name="test">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>@string/hello_world</item>
    </string-array>
</resources>

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/test" />

StateListDrawable:跟著狀態換皮膚

StateListDrawable 用來組織多個 Drawable。當它作為控件的背景或前景時,顯示哪一張會依控件狀態(focused、pressed、checked、enabled 等)自動切換。

它的 XML 根元素是 <selector>,內部可放多個 <item>,每個 item 用 android:drawable 或 android:color 指定外觀,再用 android:state_xxx 指定對應狀態。

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:color="#ff4444" android:state_focused="true" />
    <item android:color="#445566" android:state_focused="false" />
</selector>

LayerDrawable:把圖層疊起來

LayerDrawable 同樣可以裝多個 Drawable,但它是按陣列順序「疊畫」上去的,索引最大的在最上層。根元素為 <layer-list>,item 可用 android:drawable、android:id 以及 left/top/right/bottom 指定偏移。

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/ic_launcher" />
    <item android:id="@android:id/progress"   android:drawable="@drawable/b" />
</layer-list>

它常用在 SeekBar 的 progressDrawable 上,也可以拿來做圖層式合成效果:

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:gravity="center" android:src="@drawable/ic_launcher" />
    </item>
    <item android:left="25dp" android:top="25dp">
        <bitmap android:gravity="center" android:src="@drawable/ic_launcher" />
    </item>
    <item android:left="50dp" android:top="50dp">
        <bitmap android:gravity="center" android:src="@drawable/ic_launcher" />
    </item>
</layer-list>

值得注意的是,ImageView 的 src 不但能指定圖片,也能指定圖層;這裡的 gravity="center" 是相對於 ImageView 容器大小居中,而不是圖片本身。

ClipDrawable:一點一點揭開的圖

ClipDrawable 從另一張點圖上裁切出一塊顯示,裁切比例由 level 決定:0 表示完全空,10000 表示顯示整張圖。

<clip xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_launcher"
    android:clipOrientation="horizontal"
    android:gravity="top" />

只要不斷改 level,就能做出「徐徐展開」的效果:

public class MainActivity extends Activity {
    private ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.img);
        final ClipDrawable drawable = (ClipDrawable) img.getDrawable();

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0x123) {
                    drawable.setLevel(drawable.getLevel() + 20);
                }
            }
        };

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0x123;
                handler.sendMessage(msg);
                if (drawable.getLevel() >= 10000) {
                    timer.cancel();
                }
            }
        }, 0, 300);

        img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                drawable.setLevel(10000);   // 點一下直接全開
            }
        });
    }
}

補間動畫:放在 res/anim

補間動畫以 <set> 為根元素,內含 alpha(透明度)、scale(縮放)、translate(位移)、rotate(旋轉)四種變換。注意 ADT 建立專案時預設不產生 anim 目錄,需要自行建立。

<set android:duration="5000"
    android:interpolator="@android:anim/linear_interpolator"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <scale android:duration="2000"
        android:fillAfter="true"
        android:fromXScale="1.0" android:fromYScale="1.0"
        android:toXScale="1.4"  android:toYScale="0.6"
        android:pivotX="50%"    android:pivotY="50%" />
</set>
final Animation animation = AnimationUtils.loadAnimation(this, R.anim.set_test);
animation.setFillAfter(true);   // 動畫結束後保留終態
findViewById(R.id.bn).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        imageView1.startAnimation(animation);
    }
});

屬性動畫:放在 res/animator

Animator 是抽象類,實務上用它的子類:AnimatorSet、ValueAnimator、ObjectAnimator、TimeAnimator。XML 可以 <set>、<objectAnimator>、<valueAnimator> 任一為根節點,目錄同樣需要手動建立。

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout l = (LinearLayout) findViewById(R.id.container);
        l.addView(new MyAnimtionView(this));
    }

    public class MyAnimtionView extends View {
        public MyAnimtionView(Context context) {
            super(context);
            ObjectAnimator colorAnim = (ObjectAnimator)
                    AnimatorInflater.loadAnimator(context, R.animator.object_test);
            colorAnim.setEvaluator(new ArgbEvaluator());  // 讓顏色插值正確
            colorAnim.setTarget(this);
            colorAnim.start();
        }
    }
}

快速對照表

  • StateListDrawable → drawable → <selector>
  • LayerDrawable → drawable → <layer-list>
  • ShapeDrawable → drawable → <shape>
  • AnimationDrawable(補間)→ anim → <set>
  • Property Animation → animator → <set> / <objectAnimator>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved