工具是一个FrameLayout,用的时候把需要实现拖拽的view放进去就可以了。
没有事件冲突的问题。
package com.reone.loushi.customView;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.WindowManager;import android.widget.FrameLayout;/** * Created by wangxingsheng on 2017/1/15. * */public class DragLayout extends FrameLayout { private int lastX; private int lastY; private int screenWidth; private int screenHeight; public DragLayout(Context context) { super(context); init(); } public DragLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DragLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void init() { WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); screenWidth = wm.getDefaultDisplay().getWidth(); screenHeight = wm.getDefaultDisplay().getHeight(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { int ea = event.getAction(); switch (ea) { case MotionEvent.ACTION_DOWN: lastX = (int) event.getRawX(); lastY = (int) event.getRawY();//按钮初始的横纵坐标 break; case MotionEvent.ACTION_MOVE: int dx = (int) event.getRawX()-lastX; int dy = (int) event.getRawY()-lastY;//按钮被移动的距离 int l = getLeft()+dx; int b = getBottom()+dy; int r = getRight()+dx; int t = getTop()+dy; if(l<0){//处理按钮被移动到上下左右四个边缘时的情况,决定着按钮不会被移动到屏幕外边去 l = 0; r = l+getWidth(); } if(t<0){ t = 0; b = t+getHeight(); } if(r>screenWidth){ r = screenWidth; l = r - getWidth(); } if(b>screenHeight){ b = screenHeight; t = b-getHeight(); } layout(l, t, r, b); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); postInvalidate(); break; default: break; } return super.dispatchTouchEvent(event); }}
原文地址: