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

自訂 FlipView:為 View 加上 Y 軸翻轉的雙面卡片效果

編輯:關於 Android 程式設計

一般 View 只有一面。但如果我們自訂一個容器,讓它同時裝兩層子 View,再配合 Y 軸旋轉動畫,就能做出像翻書、翻卡片那樣的效果。

做法可以拆成兩塊:一個負責管理正反面與切換時機的 FlipView,以及一個負責 Y 軸旋轉與透視深度運算的 RotateAnimation。

FlipView:兩種建構方式

我們提供兩種用法:一是直接指定固定命名格式的配置檔,二是外部傳入兩個 LinearLayout 當作正面與反面。

/**
 * 兩種建立翻轉卡片的方式
 * 1:直接指定固定命名格式的 View
 * 2:外部傳入正面與反面兩個 LinearLayout
 */
public class FlipView extends LinearLayout
        implements View.OnClickListener, RotateAnimation.InterpolatedTimeListener {

    private LinearLayout m_first_ll, m_second_ll;
    private boolean enableRefresh;
    private LinearLayout view;
    private View clickView;   // 當前被點擊的那一面
    private Context context;

    public FlipView(Context context) {
        super(context);
        this.context = context;
    }

    public FlipView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    /** 方式一:從固定配置檔載入正反兩面 */
    public void initViews() {
        view = (LinearLayout) inflate(context, R.layout.flip_view, null);
        m_first_ll = (LinearLayout) view.findViewById(R.id.first_ll);
        m_second_ll = (LinearLayout) view.findViewById(R.id.second_ll);
        m_first_ll.setOnClickListener(this);
        m_second_ll.setOnClickListener(this);
        addView(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
    }

    /**
     * 方式二:外部傳入
     * @param ll1 正面
     * @param ll2 反面
     */
    public void addViews(LinearLayout ll1, LinearLayout ll2) {
        m_first_ll = ll1;
        m_second_ll = ll2;
        m_first_ll.setOnClickListener(this);
        m_second_ll.setOnClickListener(this);
        addView(m_first_ll, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        addView(m_second_ll, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
    }

    /**
     * 主動翻面
     * @param flag 0 翻到正面,1 翻到反面
     */
    public void show(int flag) {
        enableRefresh = true;
        RotateAnimation rotateAnim = null;
        float cX = this.getWidth() / 2.0f;
        float cY = this.getHeight() / 2.0f;
        if (flag == 0) {
            rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_DECREASE);
        } else if (flag == 1) {
            rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_INCREASE);
        }
        if (rotateAnim != null) {
            rotateAnim.setInterpolatedTimeListener(this);
            rotateAnim.setFillAfter(true);
            this.startAnimation(rotateAnim);
        }
    }

    @Override
    public void onClick(View v) {
        Log.d("click:", v.toString());
        enableRefresh = true;
        clickView = v;
        RotateAnimation rotateAnim = null;
        float cX = this.getWidth() / 2.0f;
        float cY = this.getHeight() / 2.0f;
        if (m_first_ll == v) {
            rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_INCREASE);
        } else if (m_second_ll == v) {
            rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_DECREASE);
        }
        if (rotateAnim != null) {
            rotateAnim.setInterpolatedTimeListener(this);
            rotateAnim.setFillAfter(true);
            this.startAnimation(rotateAnim);
        }
    }

    /** 動畫過半時才真正交換兩面的可見性 */
    @Override
    public void interpolatedTime(float interpolatedTime) {
        if (enableRefresh && interpolatedTime > 0.5f) {
            setHint();
            enableRefresh = false;
        }
    }

    public void setHint() {
        if (clickView == m_first_ll) {
            m_first_ll.setVisibility(View.GONE);
            m_second_ll.setVisibility(View.VISIBLE);
        } else if (clickView == m_second_ll) {
            m_second_ll.setVisibility(View.GONE);
            m_first_ll.setVisibility(View.VISIBLE);
        }
    }
}

關鍵在 interpolatedTime:動畫進度超過 0.5 的那一刻才切換兩面的可見性。這樣視覺上會感覺是「同一張卡翻過去」,而不是兩張卡交替閃現。

Activity 中的用法

public class FlipActivity extends Activity {
    private FlipView flipView;
    LinearLayout firstLL, secondLL;
    LinearLayout root;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
    }

    private void initViews() {
        root = (LinearLayout) LayoutInflater.from(this)
                .inflate(R.layout.activity_flip, null);
        flipView = (FlipView) root.findViewById(R.id.flip_view);

        /********* 方式一(需自行呼叫 initViews) *********/
        // firstLL  = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.flip_view1, null);
        // secondLL = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.flip_view2, null);

        /********* 方式二 *********/
        firstLL  = (LinearLayout) root.findViewById(R.id.root_ll1);
        secondLL = (LinearLayout) root.findViewById(R.id.root_ll2);
        root.removeView(firstLL);
        root.removeView(secondLL);

        flipView.addViews(firstLL, secondLL);
        setContentView(root);
    }
}

呼叫 addViews(firstLL, secondLL) 時,第一個參數是正面、第二個是反面,兩者都必須是 LinearLayout。兩種設定方式在底層其實是同一件事——只是 View 從哪裡來的差別。

RotateAnimation:旋轉與透視的運算核心

public class RotateAnimation extends Animation {
    public static final boolean DEBUG = false;

    /** 沿 Y 軸正方向看,角度遞減為逆時針 */
    public static final boolean ROTATE_DECREASE = true;
    /** 沿 Y 軸正方向看,角度遞增為順時針 */
    public static final boolean ROTATE_INCREASE = false;

    /** Z 軸最大深度 */
    public static final float DEPTH_Z = 310.0f;
    /** 動畫時長 */
    public static final long DURATION = 800l;

    private final boolean type;
    private final float centerX;
    private final float centerY;
    private Camera camera;

    public RotateAnimation(float cX, float cY, boolean type) {
        centerX = cX;
        centerY = cY;
        this.type = type;
        setDuration(DURATION);
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        // 在 建構子 之後、applyTransformation() 之前呼叫
        super.initialize(width, height, parentWidth, parentHeight);
        camera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation transformation) {
        // interpolatedTime 為動畫進度,範圍 0~1,0.5 剛好翻轉一半
        if (listener != null) {
            listener.interpolatedTime(interpolatedTime);
        }

        float from = 0.0f, to = 0.0f;
        if (type == ROTATE_DECREASE) {
            from = 0.0f;   to = 180.0f;
        } else if (type == ROTATE_INCREASE) {
            from = 360.0f; to = 180.0f;
        }

        float degree = from + (to - from) * interpolatedTime;
        boolean overHalf = (interpolatedTime > 0.5f);
        if (overHalf) {
            // 過半後減 180 度,讓文字保持正向可讀而非鏡像
            degree = degree - 180;
        }

        // 依進度做正弦式的深度變化,中段離螢幕最近
        float depth = (0.5f - Math.abs(interpolatedTime - 0.5f)) * DEPTH_Z;

        final Matrix matrix = transformation.getMatrix();
        camera.save();
        camera.translate(0.0f, 0.0f, depth);   // 與螢幕的距離
        camera.rotateY(degree);                // 以 Y 軸旋轉
        camera.getMatrix(matrix);
        camera.restore();

        if (DEBUG) {
            if (overHalf) {
                matrix.preTranslate(-centerX * 2, -centerY);
                matrix.postTranslate(centerX * 2, centerY);
            }
        } else {
            // 確保翻轉過程中心點不偏移
            // preTranslate 在縮放前平移,postTranslate 在縮放後平移,
            // 參數是「平移距離」而非目標座標。
            // 縮放以 (0,0) 為中心,因此先 preTranslate(-centerX, -centerY)
            // 把畫面中心對齊原點,完成後再 postTranslate 移回來。
            matrix.preTranslate(-centerX, -centerY);
            matrix.postTranslate(centerX, centerY);
        }
    }

    private InterpolatedTimeListener listener;

    public void setInterpolatedTimeListener(InterpolatedTimeListener listener) {
        this.listener = listener;
    }

    /** 動畫進度監聽器 */
    public static interface InterpolatedTimeListener {
        public void interpolatedTime(float interpolatedTime);
    }
}

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <cn.xindrace.viewflip.FlipView
        android:id="@+id/flip_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/root_ll1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="This is the first side" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/root_ll2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="This is the second side" />
        </LinearLayout>

    </cn.xindrace.viewflip.FlipView>
</LinearLayout>

幾個實作上的關鍵點

  • 過半才換面。把 setVisibility 綁在 interpolatedTime > 0.5,是讓動畫看起來自然的關鍵。
  • degree 減 180。過半後若不補這一步,背面的文字會呈鏡像。
  • 中心點校正不可省。Matrix 的縮放以原點為中心,用 pre/postTranslate 一組把中心搬過去再搬回來,翻轉才不會歪掉。
  • enableRefresh 是去抖動旗標。避免同一段動畫期間被重複觸發換面。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved