美文网首页
MotionEvent事件-控件随手指拖动

MotionEvent事件-控件随手指拖动

作者: MengkZhang | 来源:发表于2017-09-03 11:42 被阅读0次

    MotionEvent事件-控件随手指拖动

    private int lastX;
    private int lastY;
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //getRawX()是控件相对于父容器左上角的距离
        //获取控件的x,y坐标
        int eventX = (int) event.getRawX();
        int eventY = (int) event.getRawY();
    
    
        switch (event.getAction()) {
    
            case MotionEvent.ACTION_DOWN:
                /**记录控件的x,y坐标*/
                lastX = eventX;
                lastY = eventY;
    
                break;
    
            case MotionEvent.ACTION_MOVE:
                /**计算偏移量*/
                int dx = eventX - lastX;
                int dy = eventY - lastY;
    
                /**根据事件的偏移量来移动控件*/
                int left = mImageView.getLeft() + dx;
                int top = mImageView.getTop() + dy;
                int right = mImageView.getRight() + dx;
                int buttom = mImageView.getBottom() + dy;
                mImageView.layout(left, top, right, buttom);
    
                /**再次记录控件的x,y坐标*/
                lastX = eventX;
                lastY = eventY;
    
                break;
    
            default:
                break;
        }
            return true;/**所有的motionevent都交给imageview来处理*/
    }
    

    相关文章

      网友评论

          本文标题:MotionEvent事件-控件随手指拖动

          本文链接:https://www.haomeiwen.com/subject/ulndjxtx.html