仿QQ主界面侧滑

来源:互联网 发布:百胜软件工资怎么样 编辑:程序博客网 时间:2024/06/05 10:22
    PointF point;        //上一次触摸的位置
    PointF firstPoint;            //第一次触摸的位置

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:         //记录第一次接触的位置  
                point = new PointF(event.getX(), event.getY());
                firstPoint = new PointF(event.getX(), event.getY());        
                if (mian.getWidth() * SCALE - mian.getLeft() < 1) {        //判断位置在最右侧
                    toTran(mian.getLeft() * -1);        //移动到最左侧
                }
                break;
            case MotionEvent.ACTION_UP:         //计算抬起时的操作,判断应该在左侧还是右侧
                if (event.getX() > firstPoint.x + TRAN) {
                    toTran((int) (mian.getWidth() * SCALE) - (mian.getLeft()));
                } else if (event.getX() < firstPoint.x - TRAN) {
                    toTran(mian.getLeft() * -1);
                } else if (event.getX() > firstPoint.x) {
                    toTran(mian.getLeft() * -1);
                } else if (event.getX() < firstPoint.x) {
                    toTran((int) (mian.getWidth() * SCALE) - (mian.getLeft()));
                }
                break;
            case MotionEvent.ACTION_MOVE:           //计算移动时的操作
                float x = event.getX() - point.x;       //将要偏移量
                if (mian.getLeft() + x >= mian.getWidth() * SCALE && x >= 0)           //查看是否达到最大边界
                    x = (mian.getWidth() * SCALE) - (mian.getLeft());
                if (mian.getLeft() + x <= 0 && x <= 0)               //查看是否达到最小边界
                    x = mian.getLeft() * -1;
                point = new PointF(event.getX(), event.getY());            //记录本次触摸的位置
                mian.offsetLeftAndRight((int) (x));            //移动view视图
                break;
        }
        return true;
    }

    /**
     * @param r 将要移动的距离
     */
    private void toTran(final int r) {
        double duration = Math.abs(r * 3);        //计算动画持续时间
        TranslateAnimation animation = new TranslateAnimation(0, r, 0, 0);
        animation.setDuration((long) duration);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mian.clearAnimation();
                mian.offsetLeftAndRight(r);        //动画完成移动view
            }
        });
        mian.startAnimation(animation);            //启动动画
    }

0 0