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

Android 翻轉動畫實作:封裝可複用的 FlipableLayout

編輯:關於 Android 程式設計

前幾篇寫的動畫大多只求「跑得出效果」。這次做翻轉動畫,多加了兩個考量:實用性與可擴充性。目標不是做出一個只能套用在單一 View 上的效果,而是一個「可以翻面的 Layout」——對外實作 Flipable 介面,內部具備一定封裝性,能自由替換正反面內容,也能直接放進實際專案使用。

一、翻轉動畫的基本實作

翻轉至少需要兩個界面,可以是 View 也可以是 Layout。接著用 Android 的屬性動畫 rotationX,建立兩個 ObjectAnimator,分別負責「翻轉出現」與「翻轉消失」。

ObjectAnimator visToInvis = ObjectAnimator.ofFloat(visibleLayout, "rotationX", 0f, 90f);
ObjectAnimator invisToVis = ObjectAnimator.ofFloat(invisibleLayout, "rotationX", -90f, 0f);

關鍵在於「串接」:讓第一個動畫結束時啟動第二個,並在這個交棒點切換兩個界面的可見性。若切換時序錯了,就會看到兩個面同時出現或同時消失的破綻。

visToInvis.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator anim) {
        visibleLayout.setVisibility(View.GONE);
        invisToVis.start();
        invisibleLayout.setVisibility(View.VISIBLE);
    }
});
visToInvis.start();

把這段包成一個函式,在點擊事件中呼叫,基本效果就完成了。

二、可翻轉 Layout:FlipableLayout

先定義介面。對外只暴露一個 flip() 方法,呼叫方不需要知道內部有幾個 Layout、動畫怎麼組。

public interface Flipable {
    public void flip();
}

預設版面 flipable_relativelayout.xml。內含正面與背面兩個 LinearLayout,其中的 TextView 只是示範用的預設內容。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/front"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        android:orientation="vertical">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="visible text"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/yellow"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="invisible text"
            android:textSize="20sp" />
    </LinearLayout>
</RelativeLayout>

自訂 Layout 並載入版面。三個建構子都要補上 inflate,這是自訂 ViewGroup 的標準做法;onFinishInflate() 則是取得子 View 參照的合適時機。

public class FlipableRelativeLayout extends RelativeLayout implements Flipable {
    private LinearLayout mFontLayout;
    private LinearLayout mBackLayout;

    public FlipableRelativeLayout(Context context) {
        super(context, null);
        inflate(getContext(), R.layout.flipable_relativelayout, this);
    }

    public FlipableRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(getContext(), R.layout.flipable_relativelayout, this);
    }

    public FlipableRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        inflate(getContext(), R.layout.flipable_relativelayout, this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mFontLayout = (LinearLayout) findViewById(R.id.front);
        mBackLayout = (LinearLayout) findViewById(R.id.back);
    }

加上 setter,方便替換內容。先清掉原有子 View 再放入新的,並呼叫 invalidate() 要求重繪。

    protected void setFront(View v) {
        mFontLayout.removeAllViews();
        mFontLayout.addView(v);
        invalidate();
    }

    protected void setBack(View v) {
        mBackLayout.removeAllViews();
        mBackLayout.addView(v);
        invalidate();
    }

實作 flip()。把第一節的動畫串接邏輯搬進來即可,對外只暴露一個方法。

    @Override
    public void flip() {
        // 此處即為第一節所述的動畫串接實作
    }
}

三、示範版面 multiple_flip_example.xml

直接在 XML 中引用剛寫好的 FlipableRelativeLayout。兩個按鈕分別示範「翻轉」與「更換內容後翻轉」。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_flip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="to flip"
            android:textSize="20sp" />

        <Button
            android:id="@+id/button_change"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="change"
            android:textSize="20sp" />
    </LinearLayout>

    <com.buptfarmer.devapp.FlipableRelativeLayout
        android:id="@+id/flip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

初始化:

private void initView() {
    setContentView(R.layout.multiple_flip_example);
    mFlipButton = (Button) findViewById(R.id.button_flip);
    mFlipButton.setOnClickListener(this);
    mChangeButton = (Button) findViewById(R.id.button_change);
    mChangeButton.setOnClickListener(this);
    mFlipLayout = (FlipableRelativeLayout) findViewById(R.id.flip);
}

點擊事件:flip 按鈕直接翻轉;change 按鈕則把預設的 TextView 換成由程式碼建立的 ImageView,示範內容替換能力。

@Override
public void onClick(View v) {
    animateClickView(v, new ClickAnimation() {
        @Override
        public void onClick(View v) {
            if (v == mFlipButton) {
                mFlipLayout.flip();
            } else if (v == mChangeButton) {
                ImageView front = new ImageView(getApplicationContext());
                front.setImageResource(R.drawable.avatar);
                front.setVisibility(View.VISIBLE);

                ImageView back = new ImageView(getApplicationContext());
                back.setImageResource(R.drawable.chobber);
                back.setVisibility(View.VISIBLE);

                mFlipLayout.setFront(front);
                mFlipLayout.setBack(back);
                mFlipLayout.flip();
            }
        }
    });
}

其中 animateClickView 是先前文章實作的點擊回饋動畫,細節可參考《android 點擊效果動畫增強》。

private void animateClickView(final View v, final ClickAnimation callback)

四、多組順序翻轉

在上述基礎上再加一層:讓多個翻轉元件依序播放。做法是讓 FlipableRelativeLayout 對外提供動畫物件本身,而不是只提供「播放」這個動作。

private Animator createFlipAnimator() {
    // 建立過程同第一節
    return mVisToInvis;
}

public Animator getFlipAnimator() {
    return createFlipAnimator();
}

在範例中準備一個列表收集所有動畫:

private ArrayList mFlipList = new ArrayList();

透過遞迴遍歷整棵 View 樹,把所有 FlipableRelativeLayout 的動畫收集起來。遞迴時用 try-catch 捕捉 ClassCastException 來跳過非 ViewGroup 的節點,是個略為取巧但有效的寫法。

private void collectFlipAnim() {
    mFlipList.clear();
    traversalCollectFlip(mMainLayout);
}

private void traversalCollectFlip(ViewGroup parent) {
    if (parent == null) return;
    if (parent.getChildCount() == 0) return;

    for (int index = 0; index < parent.getChildCount(); index++) {
        if (parent.getChildAt(index) instanceof FlipableRelativeLayout) {
            mFlipList.add(((FlipableRelativeLayout) (parent.getChildAt(index)))
                    .getFlipAnimator());
            continue;
        }
        try {
            traversalCollectFlip((ViewGroup) parent.getChildAt(index));
        } catch (ClassCastException e) {
            // 不是 ViewGroup,跳過
        }
    }
}

最後用 AnimatorSet.playSequentially() 讓它們依序播放:

private void flipAll() {
    collectFlipAnim();
    AnimatorSet animSet = new AnimatorSet();
    animSet.playSequentially(mFlipList);
    animSet.start();
}

設計上的取捨

這個實作最值得沿用的地方,是把「翻轉」抽象成介面而非綁死在特定 View 上。呼叫端只認 Flipable,實作端可以自由換成 RelativeLayout、FrameLayout 或自訂群組,這讓動畫效果具備了被複用的資格。

需要留意的是,動畫期間若使用者連續快速點擊,會造成多組動畫同時進行、可見性狀態互相覆蓋。實務上建議在動畫進行中加上防重入旗標,或使用 AnimatorListener 追蹤當前狀態並忽略期間的觸發。原始程式碼中的 expand 動畫部分作者自承仍有未解的問題,這也印證了動畫狀態管理的複雜度往往高於動畫本身。

效果影片:

單組翻轉 https://v.youku.com/v_show/id_XNjY0NDA2MDI4.html

多組順序翻轉 https://v.youku.com/v_show/id_XNjY0NDgwODM2.html

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