Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

高仿 QQ HD mini 左右滑動選單欄的 Android 實作

這個效果模仿 QQ HD mini 的三欄式選單:預設顯示中間的最近會話列表;向左滑或點左上角圖示展開好友列表;向右滑或點右上角圖示展開設定一類的版面。動畫都靠 Scroller 驅動。

核心是一個自訂的 CenterLayout,繼承 LinearLayout 並攔截觸控事件:

/**
 * 可左右切換選單欄的 LinearLayout
 * @author way
 */
public class CenterLayout extends LinearLayout {

    private final static String TAG = "CenterLayout";

    public static final int LEFT   = 0x001;  // 當前顯示左選單欄
    public static final int RIGHT  = 0x002;  // 當前顯示右選單欄
    public static final int MIDDLE = 0x000;  // 當前顯示中間主界面

    private int mCurState = MIDDLE;
    public final int MENU_border_Width = 50;  // 邊欄寬度

    private Scroller mScroller;
    private LinearLayout leftLayout, rightLayout, childLayout;
    private Context context;
    private boolean fling;
    private boolean mIsBeingDragged = false;
    private int mTouchSlop;

    private float mLastMotionX, mLastMotionY;
    private int mActivePointerId = INVALID_POINTER;
    private static final int INVALID_POINTER = -1;

    int menuWidth = 0;
    int moveWidth = 0;

    public CenterLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CenterLayout(Context context) {
        super(context);
        initView(context);
    }

    public Scroller getScroller() {
        return mScroller;
    }

    public void initView(Context context) {
        this.context  = context;
        this.menuWidth = MENU_border_Width;
        this.mScroller = new Scroller(context,
            AnimationUtils.loadInterpolator(context,
                android.R.anim.overshoot_interpolator));

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
        mCurState  = MIDDLE;
    }

    /** 取得螢幕寬度 */
    private int getViewWidthInPix(Context context) {
        int viewWidthInPix = -1;
        if (viewWidthInPix == -1) {
            WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
            viewWidthInPix = manager.getDefaultDisplay().getWidth();
        }
        return viewWidthInPix;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.layout(child.getLeft() + moveWidth, child.getTop(),
                child.getRight() + moveWidth, child.getBottom());
        }
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), 0);
            postInvalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
            return true;   // 攔截,不傳給 child view
        }

        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
            final float x = ev.getX();
            final float y = ev.getY();
            if (!inChild((int) x, (int) y)) {
                mIsBeingDragged = false;
                break;         // 超出邊界,return false 交給子 view
            }
            mLastMotionX = x;
            mLastMotionY = y;
            mActivePointerId = ev.getPointerId(0);
            mIsBeingDragged = !mScroller.isFinished();
            break;
        }
        case MotionEvent.ACTION_MOVE: {
            final int activePointerId = mActivePointerId;
            if (activePointerId == INVALID_POINTER) {
                break;
            }
            final int pointerIndex = ev.findPointerIndex(activePointerId);
            final float x = ev.getX(pointerIndex);
            final float y = ev.getY(pointerIndex);
            final int xDiff = (int) Math.abs(x - mLastMotionX);
            final int yDiff = (int) Math.abs(y - mLastMotionY);
            if (xDiff > mTouchSlop && yDiff < xDiff) {
                mIsBeingDragged = true;
            }
            break;
        }
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            mIsBeingDragged = false;
            mActivePointerId = INVALID_POINTER;
            scrollToScreen();
            break;
        }
        return mIsBeingDragged;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN
            && !inChild((int) event.getX(), (int) event.getY())) {
            return false;
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            return true;   // 本 VIEW 消化掉

        case MotionEvent.ACTION_MOVE:
            final int activePointerIndex = event.findPointerIndex(mActivePointerId);
            final float x = event.getX(activePointerIndex);
            final float y = event.getY(activePointerIndex);
            final int distanceX = (int) -(x - mLastMotionX);

            // 滑動過程中就要顯示新的 brotherView,否則放手時會突然變成新 view,影響體驗
            if (distanceX < 0 && getScrollX() < 0 && leftLayout != null) {
                setBrotherVisibility(LEFT);
            } else if (distanceX > 0 && getScrollX() > 0 && rightLayout != null) {
                setBrotherVisibility(RIGHT);
            } else {
                setBrotherVisibility(MIDDLE);
            }

            scrollBy((int) distanceX, 0);
            mLastMotionX = x;
            mLastMotionY = y;
            break;

        case MotionEvent.ACTION_UP:
            mIsBeingDragged = false;
            mActivePointerId = INVALID_POINTER;
            scrollToScreen();
            break;

        default:
            return super.onTouchEvent(event);
        }
        return mIsBeingDragged;
    }

    private void scrollToScreen() {
        int scrollDistance = 0;
        if (Math.abs(getScrollX()) > getWidth() / 2)
            scrollDistance = (getScrollX() > 0)
                ? getWidth() - menuWidth - getScrollX()
                : -(getWidth() - menuWidth - Math.abs(getScrollX()));
        else
            scrollDistance = -getScrollX();

        int distance = scrollDistance + getScrollX();
        if (distance > 0)      mCurState = RIGHT;
        else if (distance < 0) mCurState = LEFT;
        else                   mCurState = MIDDLE;

        mScroller.startScroll(getScrollX(), 0, scrollDistance, 0,
            Math.abs(scrollDistance) * 2);
        invalidate();
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (Math.abs(velocityX) > ViewConfiguration.get(context)
                .getScaledMinimumFlingVelocity()) {
            fling = true;
            scrollToScreen();
        }
        return fling;
    }

    private boolean inChild(int x, int y) {
        if (getChildCount() > 0) {
            final int scrollX = mScroller.getCurrX();
            return !(scrollX + x < 0 || scrollX + x > getWidth()
                     || y < 0 || y > getHeight());
        }
        return false;
    }

    /** 設定當前顯示的 view */
    public void setPage(int whichpg) {
        int targetX = 0, moveDistance = 0;
        if (whichpg == LEFT) {
            targetX  = -(getViewWidthInPix(context) - menuWidth);
            mCurState = LEFT;
        } else if (whichpg == RIGHT) {
            targetX  = getViewWidthInPix(context) - menuWidth;
            mCurState = RIGHT;
        } else {
            mCurState = MIDDLE;
        }
        setBrotherVisibility(whichpg);
        moveDistance = targetX - getScrollX();
        mScroller.startScroll(getScrollX(), 0, moveDistance, 0,
            Math.abs(moveDistance) * 2);
        invalidate();
    }

    /** 回傳當前顯示的 view */
    public int getPage() {
        return mCurState;
    }

    public void addChildView(View child) {
        this.childLayout.addView(child);
    }

    /** 設定 BrotherView */
    public void setBrotherLayout(LinearLayout left, LinearLayout right) {
        this.leftLayout  = left;
        this.rightLayout = right;
    }

    /** 依當前狀態顯示或隱藏 view */
    private void setBrotherVisibility(int state) {
        switch (state) {
        case LEFT:
            rightLayout.setVisibility(View.GONE);
            leftLayout.setVisibility(View.VISIBLE);
            break;
        case RIGHT:
            rightLayout.setVisibility(View.VISIBLE);
            leftLayout.setVisibility(View.GONE);
            break;
        case MIDDLE:
            break;
        default:
            break;
        }
    }
}
Copyright © Linux教程網 All Rights Reserved