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

Android 動畫實作:讓 Activity 像卡片一樣 180 度翻面

編輯:關於 Android 程式設計

把 Activity 想成一張紙卡,正面與背面各自有內容,點擊任一面的翻轉按鈕,整張卡就以畫面中心為軸心(Z 軸的翻轉中心也可以自行調整)旋轉過來,這就是本文要實作的翻面效果。

先看成果預覽:







整體思路

因為整個效果只涉及一個 Activity,所以正反兩面的版面必須寫在同一個 layout 檔案裡,這就需要在佈局層面上做一點設計。

這裡的做法是用 FrameLayout 當外層容器,裡面放兩個重疊的 RelativeLayout 分別代表正面與背面。其他佈局當然也可以,關鍵是初始狀態下要把其中一面設為 android:visibility="gone"。

<?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">

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- 背面 -->
        <RelativeLayout
            android:id="@+id/relative_layout_two"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#50616d"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <TextView
                android:id="@+id/tv_two"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="布局2"
                android:textColor="#789456"
                android:textSize="30sp" />

            <Button
                android:id="@+id/rotate_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerInParent="true"
                android:text="翻轉" />
        </RelativeLayout>

        <!-- 正面 -->
        <RelativeLayout
            android:id="@+id/relative_layout_one"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#0aa344"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <TextView
                android:id="@+id/tv_one"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="布局1"
                android:textColor="#123456"
                android:textSize="30sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/rotate_next"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerInParent="true"
                android:text="翻轉" />
        </RelativeLayout>
    </FrameLayout>
</LinearLayout>

一個容易忽略的細節:兩個 RelativeLayout 都要加上 android:focusable="true" 與 android:focusableInTouchMode="true"。這兩個屬性用來隔離兩面的觸控事件,讓目前可見的那一面能正常接收點擊,隱藏面的監聽則失效;少了它,點擊行為很容易亂掉。

自訂 3D 旋轉動畫

接下來是動畫本體。先決定翻轉的軸心位置,透過傳入 X、Y、Z 三軸座標來指定;再用 Camera 依給定的角度做旋轉。核心類別 Rotate3D 如下:

/**
 * 3D 旋轉動畫核心類
 */
public class Rotate3D extends Animation {

    private final float mFromDegrees;   // 起始角度
    private final float mToDegrees;     // 結束角度
    private final float mCenterX;       // X 軸中心點
    private final float mCenterY;       // Y 軸中心點
    private final float mDepthZ;        // Z 軸中心點
    private final boolean mReverse;     // 是否需要扭曲
    private Camera mCamera;             // 攝像頭

    public Rotate3D(float fromDegrees, float toDegrees,
                    float centerX, float centerY,
                    float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        // 計算中間角度
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;
        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);        // 翻轉
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

Activity 中的組裝

整個翻轉被拆成兩個階段:第一階段把目前這一面轉到垂直於螢幕的位置(此時正反兩面都看不見),第二階段再把另一面從垂直位置轉回正面朝使用者。

public class TestRotateActivity extends Activity {

    private TextView tvOne;
    private Button btnRotateNext;
    private TextView tvTwo;
    private Button btnRotateBack;
    private FrameLayout flContainer;
    private RelativeLayout relativeLayout1;
    private RelativeLayout relativeLayout2;

    // 目前顯示的索引:1 表示正面,2 表示背面
    private int index = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rotate);
        initView();
        registerClickListener();
    }

    private void initView() {
        tvOne = (TextView) findViewById(R.id.tv_one);
        tvTwo = (TextView) findViewById(R.id.tv_two);
        flContainer = (FrameLayout) findViewById(R.id.frame_layout);
        relativeLayout1 = (RelativeLayout) findViewById(R.id.relative_layout_one);
        relativeLayout2 = (RelativeLayout) findViewById(R.id.relative_layout_two);
        btnRotateNext = (Button) findViewById(R.id.rotate_next);
        btnRotateBack = (Button) findViewById(R.id.rotate_back);
    }

    private void registerClickListener() {
        tvOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(TestRotateActivity.this, "one", Toast.LENGTH_SHORT).show();
            }
        });
        tvTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(TestRotateActivity.this, "two", Toast.LENGTH_SHORT).show();
            }
        });

        View.OnClickListener flipListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (index == 1) {
                    // 第一階段:正面轉向 90 度
                    applyRotation(1, 0, 90);
                    index = 0;
                } else {
                    // 第一階段:背面轉向 -90 度
                    applyRotation(0, 0, -90);
                    index = 1;
                }
            }
        };
        btnRotateNext.setOnClickListener(flipListener);
        btnRotateBack.setOnClickListener(flipListener);
    }

    /**
     * 執行第一階段動畫
     */
    private void applyRotation(int tag, float start, float end) {
        final float centerX = flContainer.getWidth() / 2.0f;
        final float centerY = flContainer.getHeight() / 2.0f;
        final float depthZ = 500.0f;

        Rotate3D rotation = new Rotate3D(start, end, centerX, centerY, depthZ, true);
        rotation.setDuration(300);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(tag));
        flContainer.startAnimation(rotation);
    }

    /**
     * 第一階段動畫監聽器
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int tag;

        private DisplayNextView(int tag) {
            this.tag = tag;
        }

        public void onAnimationStart(Animation animation) { }

        public void onAnimationEnd(Animation animation) {
            // 此時整個 Activity 垂直於螢幕,接著執行第二階段
            flContainer.post(new SwapViews(tag));
            adjustVisiable();
        }

        public void onAnimationRepeat(Animation animation) { }
    }

    /**
     * 執行第二階段動畫
     */
    private final class SwapViews implements Runnable {
        private final int tag;

        public SwapViews(int position) {
            tag = position;
        }

        public void run() {
            if (tag == 0) {
                showView(relativeLayout1, relativeLayout2, 90, 0);
            } else if (tag == 1) {
                showView(relativeLayout2, relativeLayout1, -90, 0);
            }
        }
    }

    /**
     * 顯示第二個視圖
     */
    private void showView(RelativeLayout showView, RelativeLayout hiddenView,
                          int startDegree, int endDegree) {
        float centerX = showView.getWidth() / 2.0f;
        float centerY = showView.getHeight() / 2.0f;
        float centerZ = 500.0f;

        if (centerX == 0 || centerY == 0) {
            // getMeasuredWidth() 之前必須先 measure,否則會出異常
            showView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            centerX = showView.getMeasuredWidth() / 2.0f;
            centerY = showView.getMeasuredHeight() / 2.0f;
        }

        hiddenView.setVisibility(View.GONE);
        showView.setVisibility(View.VISIBLE);

        Rotate3D rotation = new Rotate3D(startDegree, endDegree,
                centerX, centerY, centerZ, false);
        rotation.setDuration(300);
        rotation.setInterpolator(new DecelerateInterpolator());
        flContainer.startAnimation(rotation);
    }

    /**
     * 切換兩面的 visibility
     */
    private void adjustVisiable() {
        tvOne.setVisibility(tvOne.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        tvTwo.setVisibility(tvTwo.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
    }
}

以上就是 Activity 翻面動畫的完整做法。第一階段用加速插值模擬被翻離視線的感覺,第二階段用減速插值讓新的一面「落」進畫面,兩段時間相等才能接得順。若有可以調整的地方,歡迎指教。

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