MotionEvent事件-控件随手指拖动

2017-09-03  本文已影响0人  MengkZhang

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来处理*/
}
上一篇下一篇

猜你喜欢

热点阅读