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

自訂控制項實作:仿卡片堆疊點擊置頂的滑動效果

編輯:關於 Android 程式設計

先看看要模仿的對象是什麼樣子:

行為規則其實只有一條:只有最頂端那張卡片會響應點擊事件。若點到的不是最頂端,就先把被點的卡片移到最前面,再播放移動動畫。技術難點在於子 View 被移到前面時的過渡動畫該怎麼處理。

規則釐清之後,實作方向就明確了。先看我們做出來的效果:

拆問題

範例裡放了一個按鈕與兩個 View 進容器,只有位於最前面(也就是最上層)的那個會接收事件。因此我們繼承 ViewGroup,命名為 ExchageCarldView,先從 onMeasure() 與 onLayout() 開始。

onMeasure 與 onLayout

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    measureChildren(widthMeasureSpec, heightMeasureSpec);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

onMeasure() 這裡什麼都沒做,只是把量測交給系統預設實作。真正的邏輯都在 onLayout():

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int count = getChildCount();

    if (mIsExchageAnimation) {
        // 動畫中的分支
        for (int i = 0; i < count; i++) {
            if (mTouchIndex > i) {
                // 被點擊卡片之上的那些不需要改變 layout
                continue;
            }
            View view = getChildAt(i);
            // 緩存第一次的 view 資訊,也就是動畫剛開始時的位置
            cacheViewTopAndBottomIfneed(i, view);

            if (count - 1 == i) {
                // 最上層的布局:計算它總共該走多少高度
                int total_dis = view.getHeight() / 2 * (count - 1 - mTouchIndex);
                // 計算目前的線性距離
                int now_dis = (int) (total_dis
                        * (System.currentTimeMillis() - mAnimationStartTime)
                        / Default_animtion_time);
                // 不能超過 total_dis
                int dis = Math.min(now_dis, total_dis);
                view.layout(view.getLeft(), mViewsTopCache.get(i) + dis,
                        view.getRight(), mViewsBottomCache.get(i) + dis);
            } else {
                // 除最上層之外的其他卡片:每個都移動 view.height 的 1/2
                int total_dis = view.getHeight() / 2;
                int now_dis = (int) (total_dis
                        * (System.currentTimeMillis() - mAnimationStartTime)
                        / Default_animtion_time);
                int dis = Math.min(now_dis, total_dis);
                // 往上移動
                view.layout(view.getLeft(), mViewsTopCache.get(i) - dis,
                        view.getRight(), mViewsBottomCache.get(i) - dis);
            }
            // 檢測動畫是否結束
            checkAnimation();
        }
    } else {
        // 初始時配置卡片,每張只露出高度的一半
        mTotalHight = 0;
        for (int i = 0; i < count; i++) {
            View view = getChildAt(i);
            view.layout(getPaddingLeft(), mTotalHight,
                    view.getMeasuredWidth(), mTotalHight + view.getMeasuredHeight());
            mTotalHight += view.getMeasuredHeight() / 2;
        }
    }
}

兩個分支涇渭分明:一個是動畫進行中,一個是靜止狀態。這裡刻意用「高度的一半」作為卡片間的重疊量,做出堆疊的視覺。

至于為什麼用 layout() 而不是 draw() 做動畫,後面談到 bringToFront() 時就會明白。

為什麼要緩存位置

/**
 * 緩存 view 的頂部與底部資訊
 */
void cacheViewTopAndBottomIfneed(int i, View view) {
    int viewtop = mViewsTopCache.get(i, -1);
    if (viewtop == -1) {
        mViewsTopCache.put(i, view.getTop());
    }
    int viewbttom = mViewsBottomCache.get(i, -1);
    if (viewbttom == -1) {
        mViewsBottomCache.put(i, view.getBottom());
    }
}

因為 onLayout() 會被反覆呼叫,而 getTop() 每次回傳的都是上一次配置後的新值。若直接拿它當計算基準,位移就會不斷累加而失去對齊點。所以必須在動畫開始時把初始位置存下來,後續每次都從這個基準算起。

觸控事件怎麼分派

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (mIsExchageAnimation) {
        // 動畫進行中,吃掉事件
        return true;
    }

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        mTouchIndex = getTouchChildIndex(event); // 取得被點擊 View 的 index
        if (mTouchIndex != -1 && mTouchIndex != getChildCount() - 1) {
            // 點到的是最後一張時不需要啟動動畫
            startAnimation();
        }
    }

    // 只響應最後一張卡片的點擊
    if (mTouchIndex == getChildCount() - 1) {
        return super.dispatchTouchEvent(event);
    } else {
        // 其他點擊事件吃掉
        return true;
    }
}

邏輯很直接:動畫中就把事件吃掉避免重入;ACTION_DOWN 時找出被點的 index,若點到的不是最上層就啟動動畫;最後再判斷要不要把事件往下傳——只有最上層那張才配得上 super.dispatchTouchEvent()。

找出被點到的是哪張卡片

/**
 * 依點擊位置取得 child 的 index
 */
int getTouchChildIndex(MotionEvent event) {
    for (int i = 0; i < getChildCount(); i++) {
        View view = getChildAt(i);
        Rect r = new Rect();
        view.getGlobalVisibleRect(r);
        r = new Rect(r.left, r.top, r.right, r.bottom - view.getHeight() / 2);
        // 注意這裡取的是上半部分來做判定
        if (r.contains((int) event.getRawX(), (int) event.getRawY())) {
            return i;
        }
    }
    return -1;
}

因為卡片彼此重疊了一半,若用完整範圍判定,同一個座標會命中多張卡片。把判定範圍縮到上半部,就能唯一對應到一張。

啟動動畫

/** 開始動畫 */
private void startAnimation() {
    mIsExchageAnimation = true;
    mViewsBottomCache.clear();
    mViewsTopCache.clear();
    mAnimationStartTime = System.currentTimeMillis();

    View view = getChildAt(mTouchIndex);
    view.bringToFront(); // 這句是關鍵

    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            mAnimationHandler.sendEmptyMessage(0);
        }
    }, 0, 24);
}

先清掉緩存、記錄起始時間,然後 view.bringToFront()。這一句會把該子 View 移到子陣列的最後一個位置,而繪製順序是由前往後,所以它就成了視覺上的最上層。這也是前面選擇用 onLayout() 而非 draw() 做動畫的原因——位置交給 layout 系統管,繪製順序交給 bringToFront() 管,兩者不必互相遷就。

之後開一個每 24 毫秒觸發一次的計時器,定時送訊息給 Handler。這個 Handler 什麼也不做,只呼叫 requestLayout(),讓系統重新走一遍 onLayout(),動畫就靠這樣一幀一幀推進。

重點回顧

1. 卡片露出的比例,這裡直接取容器高度的一半;

2. 用 layout() 改變位置來做動畫,而非在 draw() 裡計算;

3. 最重要的觀念是理解 bringToFront() 對子 View 陣列順序的影響;

4. 動畫開始前務必緩存 view 的 top 與 bottom,作為計算基準。

完整程式碼

/**
 * @author edsheng
 * @filename ExchageCarldView.java
 * @date 2015/3/12
 * @version v1.0
 */
public class ExchageCarldView extends ViewGroup {

    private int mTotalHight = 0;                        // 總高度
    private boolean mIsExchageAnimation = false;        // 是否正在播放交換動畫
    private SparseIntArray mViewsTopCache = new SparseIntArray();    // 卡片頂部邊界快取
    private SparseIntArray mViewsBottomCache = new SparseIntArray(); // 卡片底部邊界快取
    private long mAnimationStartTime = 0;               // 動畫開始時間
    private long Default_animtion_time = 250;           // 動畫時間(毫秒)
    private Timer timer;                                // 動畫計時器
    private int mTouchIndex = -1;                       // 被點擊的 index

    Handler mAnimationHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            requestLayout(); // 更新版面以推進動畫
        }
    };

    public ExchageCarldView(Context context) {
        super(context);
    }

    /** 緩存 view 的頂部與底部資訊 */
    void cacheViewTopAndBottomIfneed(int i, View view) {
        int viewtop = mViewsTopCache.get(i, -1);
        if (viewtop == -1) {
            mViewsTopCache.put(i, view.getTop());
        }
        int viewbttom = mViewsBottomCache.get(i, -1);
        if (viewbttom == -1) {
            mViewsBottomCache.put(i, view.getBottom());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /** 檢測並停止動畫 */
    private void checkAnimation() {
        if (Math.abs(System.currentTimeMillis() - mAnimationStartTime) >= Default_animtion_time) {
            mAnimationHandler.removeMessages(0);
            timer.cancel();
            mIsExchageAnimation = false;
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();

        if (mIsExchageAnimation) {
            // 動畫中的分支
            for (int i = 0; i < count; i++) {
                if (mTouchIndex > i) {
                    continue;
                }
                View view = getChildAt(i);
                cacheViewTopAndBottomIfneed(i, view);

                if (count - 1 == i) {
                    // 最上層:向下移動
                    int total_dis = view.getHeight() / 2 * (count - 1 - mTouchIndex);
                    int now_dis = (int) (total_dis
                            * (System.currentTimeMillis() - mAnimationStartTime)
                            / Default_animtion_time);
                    int dis = Math.min(now_dis, total_dis);
                    view.layout(view.getLeft(), mViewsTopCache.get(i) + dis,
                            view.getRight(), mViewsBottomCache.get(i) + dis);
                } else {
                    // 其餘卡片:向上移動高度的一半
                    int total_dis = view.getHeight() / 2;
                    int now_dis = (int) (total_dis
                            * (System.currentTimeMillis() - mAnimationStartTime)
                            / Default_animtion_time);
                    int dis = Math.min(now_dis, total_dis);
                    view.layout(view.getLeft(), mViewsTopCache.get(i) - dis,
                            view.getRight(), mViewsBottomCache.get(i) - dis);
                }
                checkAnimation();
            }
        } else {
            // 初始化卡片配置
            mTotalHight = 0;
            for (int i = 0; i < count; i++) {
                View view = getChildAt(i);
                view.layout(getPaddingLeft(), mTotalHight,
                        view.getMeasuredWidth(), mTotalHight + view.getMeasuredHeight());
                mTotalHight += view.getMeasuredHeight() / 2;
            }
        }
    }

    /** 開始動畫 */
    private void startAnimation() {
        mIsExchageAnimation = true;
        mViewsBottomCache.clear();
        mViewsTopCache.clear();
        mAnimationStartTime = System.currentTimeMillis();

        View view = getChildAt(mTouchIndex);
        view.bringToFront();

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mAnimationHandler.sendEmptyMessage(0);
            }
        }, 0, 24);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mIsExchageAnimation) {
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mTouchIndex = getTouchChildIndex(event);
            if (mTouchIndex != -1 && mTouchIndex != getChildCount() - 1) {
                startAnimation();
            }
        }
        if (mTouchIndex == getChildCount() - 1) {
            return super.dispatchTouchEvent(event);
        } else {
            return true;
        }
    }

    /** 依點擊位置取得 child 的 index */
    int getTouchChildIndex(MotionEvent event) {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            Rect r = new Rect();
            view.getGlobalVisibleRect(r);
            r = new Rect(r.left, r.top, r.right, r.bottom - view.getHeight() / 2);
            if (r.contains((int) event.getRawX(), (int) event.getRawY())) {
                return i;
            }
        }
        return -1;
    }
}

測試用程式碼

public class CardExchageDemo extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        ExchageCarldView exchageView = new ExchageCarldView(this);

        View view = new View(this);
        view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 300));
        view.setBackgroundColor(Color.YELLOW);
        exchageView.addView(view);

        View view1 = new View(this);
        view1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 300));
        view1.setBackgroundColor(Color.BLUE);
        exchageView.addView(view1);

        Button view2 = new Button(this);
        view2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(CardExchageDemo.this, "hello", 0).show();
            }
        });
        view2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 300));
        view2.setBackgroundColor(Color.RED);
        view2.setText("hello");
        exchageView.addView(view2);

        exchageView.setBackgroundColor(Color.GREEN);
        setContentView(exchageView);
    }
}

最後補一個實作面的建議:範例用 Timer 加 Handler 驅動動畫,能跑但並不理想。Timer 會另開一條執行緒,而 requestLayout() 必須在 UI 執行緒呼叫,這裡是透過 Handler 間接達成,繞了一層。更直接的寫法是改用 postInvalidateOnAnimation() 或 ValueAnimator,都能省去自建計時器的麻煩,也更容易在 Activity 銷毀時一併取消,避免洩漏。

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