Android拖拽,简单的实现方法。先看效果:

003503733.gif

是使用OnTouchListener监听按下、移动、抬起3个事件来实现拖拽效果。

首先需要给目标ImageView设置一个监听器:

ImageView tabImg = (ImageView) rootView.findViewById(R.id.tab_img);
tabImg.setBackgroundResource(R.drawable.blink);
tabImg.setOnTouchListener(new TabImgTouch());

然后是重点——TabImgTouch:

private class TabImgTouch implements OnTouchListener {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        long downTime = 0, moveTime = 0;
        int touchX = 0, touchY = 0;
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downTime = event.getDownTime();
            break;
        case MotionEvent.ACTION_MOVE:
            moveTime = event.getEventTime();
            if (moveTime - downTime > 1500) {// 长按
                v.setAlpha(0.5f);//透明度
                touchX = (int) (event.getRawX());//相对于屏幕左上的X坐标
                // my = (int) (event.getRawY() - 50);//状态栏和标题栏
                touchY = (int) (event.getRawY() - 150);
                v.layout(touchX - v.getWidth() / 2, touchY - v.getHeight()
                        / 2, touchX + v.getWidth() / 2,
                        touchY + v.getHeight() / 2);//定位
            }
            break;
        case MotionEvent.ACTION_UP:
            v.setAlpha(1f);
            break;
        default:
            break;
        }
        return true;//Attention!
    }
}

如此,很简单的就实现一个简单的拖拽,更炫的效果请相信自己尽情发挥。