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

Android 卡片翻轉動畫實作:Animator、Fragment 與自訂轉場完整教學

編輯:關於 Android 程式設計

卡片翻轉(Card Flip)是很經典的動畫效果:兩面內容各自獨立,切換時模擬實體卡片沿 Y 軸旋轉 180 度。Android 從 3.0 起提供的 ObjectAnimator 與 Fragment 轉場機制,讓這個效果可以用純宣告式的方式完成,幾乎不需要自己算矩陣。

涉及的檔案大致如下:

src/CardFlipActivity.java
animator/card_flip_left_in.xml
animator/card_flip_left_out.xml
animator/card_flip_right_in.xml
animator/card_flip_right_out.xml
layout/fragment_card_back.xml
layout/fragment_card_front.xml

一、建立四個 Animator

翻轉需要四個動畫:正面「向左轉出」與「自左轉入」,背面「自右轉入」與「向右轉出」。每個動畫都由「旋轉」加上「透明度切換」兩段組合而成,關鍵技巧是在旋轉剛好進行到一半時切換 alpha,讓畫面不會出現鏡像的錯字。

card_flip_left_in.xml(正面自左轉入):

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 旋轉前先把 alpha 設為 0 -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:duration="0" />

    <!-- 旋轉 -->
    <objectAnimator
        android:valueFrom="-180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- 旋轉到一半時把 alpha 設回 1 -->
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

card_flip_left_out.xml(正面向左轉出):旋轉從 0 到 180,並在 startOffset 為一半時把 alpha 從 1 降到 0。

card_flip_right_in.xml(背面自右轉入):旋轉從 180 到 0,alpha 的處理與 left_in 相同。

card_flip_right_out.xml(背面向右轉出):旋轉從 0 到 -180,並在中途把 alpha 降為 0。

別忘了在 res/values/integers.xml 中定義兩個整數:

<integer name="card_flip_time_full">300</integer>
<integer name="card_flip_time_half">150</integer>

二、建立卡片兩面的版面

卡片的每一面都是一份獨立版面,內容可以完全自由——兩段文字、兩張圖片、或任何 View 組合。以下是一面顯示文字的例子:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#a6c"
    android:padding="16dp"
    android:gravity="bottom">

    <TextView android:id="@android:id/text1"
        style="?android:textAppearanceLarge"
        android:textStyle="bold"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/card_back_title" />

    <TextView style="?android:textAppearanceSmall"
        android:textAllCaps="true"
        android:textColor="#80ffffff"
        android:textStyle="bold"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/card_back_description" />
</LinearLayout>

另一面則是一張圖片:

<ImageView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image1"
    android:scaleType="centerCrop"
    android:contentDescription="@string/description_image_1" />

三、建立兩個 Fragment

為正反兩面各建一個 Fragment,在 onCreateView() 中回傳對應版面:

public class CardFlipActivity extends Activity {
    ...
    /** 卡片正面 */
    public class CardFrontFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_card_front, container, false);
        }
    }

    /** 卡片背面 */
    public class CardBackFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_card_back, container, false);
        }
    }
}

四、加入容器並顯示預設面

Activity 的版面只需要一個空的 FrameLayout 作為容器,Fragment 在執行期動態放入:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_card_flip);

    if (savedInstanceState == null) {
        getFragmentManager()
            .beginTransaction()
            .add(R.id.container, new CardFrontFragment())
            .commit();
    }
}

加上 savedInstanceState == null 的判斷很重要——否則每次旋螢幕或回前台時都會重複疊加 Fragment。

五、執行翻轉

翻轉方法要做三件事:設定自訂動畫、替換目前 Fragment、把舊的 Fragment 推進返回堆疊(這樣按返回鍵能翻回正面)。

private boolean mShowingBack;

private void flipCard() {
    if (mShowingBack) {
        getFragmentManager().popBackStack();
        return;
    }

    mShowingBack = true;

    getFragmentManager()
        .beginTransaction()
        // 自訂正反兩面的旋轉動畫
        .setCustomAnimations(
            R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            R.animator.card_flip_left_in,  R.animator.card_flip_left_out)
        // 以背面 Fragment 取代目前內容
        .replace(R.id.container, new CardBackFragment())
        // 加入返回堆疊,讓返回鍵能翻回正面
        .addToBackStack(null)
        .commit();
}

setCustomAnimations() 的四個參數順序是固定的:前兩個是「新 Fragment 進入 / 舊 Fragment 離開」,後兩個則是「返回堆疊時反向播放」的動畫。順序寫錯會導致翻轉方向看起來很怪。

實務提醒

  • 記得同步 mShowingBack 狀態:使用者按返回鍵翻回正面時不會經過 flipCard() 的設定分支,狀態旗標可能與畫面不同步。可在 onBackPressed() 中一併更新。
  • 避免在動畫進行中重複觸發:快速連續點擊會造成多個 Fragment 堆疊,建議加上防抖或動畫旗標。
  • Fragment 版本:範例使用 platform 的 FragmentManager;若專案走 AndroidX,改用 androidx.fragment.app.FragmentActivity 與 FragmentTransaction.setCustomAnimations(),寫法一致。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved