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

為圖片加上切換動畫:ImageSwitcher 搭配 Gallery

編輯:Android 開發教學

前一節介紹了如何組合使用 Gallery 與 ImageView。但有時候你並不希望點擊縮圖後,圖片就「突然地」出現在 ImageView 裡,而是希望能加上切換動畫。這時就該改用 ImageSwitcher 與 Gallery 搭配。

一、建立專案 ImageSwitcher

二、main.xml

<?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="fill_parent"
        android:layout_height="wrap_content"
        android:text="Images of San Francisco" />

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageSwitcher
        android:id="@+id/switcher1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />
</LinearLayout>

三、在 res/values 下建立 attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery1">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>
</resources>

四、準備圖片

把圖片放進 res/drawable-mdpi。

兩個實作上的關鍵

第一,ImageSwitcher 是 ViewSwitcher 的子類,它同一時間只允許有一個子檢視,因此在程式中設定圖片前必須先 setFactory 回傳一個新的 ImageView,並在每次切換前呼叫 setImageDrawable——直接 addView 會拋出例外。

第二,動畫要透過 setInAnimation() 與 setOutAnimation() 設定,通常放在 res/anim 中以 XML 定義淡入淡出或推入效果,這樣切換就會有平順的過場,而不是硬邦邦地跳換。

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