欢迎关注Android技术分享公众号(小红人)。
http://blog.csdn.net/kymjs/article/details/43817733
这篇文章是基于夏安明写的一个可以移动item的Demo改写的,因为原代码有一些BUG,比如adapter不能使用ViewHolder优化(这个问题应该是最大的问题)再比如不能使用上下拉刷新功能(这个是我额外添加的功能,不知道的可以去看看开源中国手机客户端的便签功能)
在Android开发中,我们常常用到ListView和GridView,而有的时候系统的ListView,GridView并不能满足我们的需求,所以我们需要自己定义一个ListView或者GridView,今天这篇文章就给大家来自定义GridView的控件,GridView主要是来显示网格的控件,在Android的开发中使用很普通,相对于TextView,Button这些控件来说要来的复杂些,今天给大家带来长按GridView的item,然后将其拖拽其他item上面,使得GridView的item发生交换,比较典型的就是我们的Launcher,网上有很多关于GridView的拖动的Demo,但是大部分都是相同的,而且存在一些Bug,而且大部分都是点击GridView的item然后进行拖动,或者item之间不进行实时交换,今天给大家更加详细的介绍GridView拖拽,并且将Demo做的更完美,大家更容易接受,也许很多人听到这个感觉实现起来很复杂,就关掉的这篇文章,其实告诉大家,只要知道了思路就感觉一点都不复杂了,不信大家可以接着往下看看,首先还是跟大家说说实现的思路
-
根据手指按下的X,Y坐标来获取我们在GridView上面点击的item
-
手指按下的时候使用Handler和Runnable来实现一个定时器,假如定时时间为1000毫秒,在1000毫秒内,如果手指抬起了移除定时器,没有抬起并且手指点击在GridView的item所在的区域,则表示我们长按了GridView的item
-
如果我们长按了item则隐藏item,然后使用WindowManager来添加一个item的镜像在屏幕用来代替刚刚隐藏的item
-
当我们手指在屏幕移动的时候,更新item镜像的位置,然后在根据我们移动的X,Y的坐标来获取移动到GridView的哪一个位置
-
到GridView的item过多的时候,可能一屏幕显示不完,我们手指拖动item镜像到屏幕下方,要触发GridView想上滚动,同理,当我们手指拖动item镜像到屏幕上面,触发GridView向下滚动
-
GridView交换数据,刷新界面,移除item的镜像
看完上面的这些思路你是不是找到了些感觉了呢?下面为大家讲讲核心部分——点击事件处理。
Android事件分发对于自定义控件很重要,简单说下,当我们点击GridView的Item,先会去执行dispatchTouchEvent()方法将事件分发下去,所以我们要重写dispatchTouchEvent()方法在手指按下的时候根据pointToPosition()方法来获取我们按下的item的position,根据getChildAt()方法来获取该position上面所对应的View, 并且开启长按的定时器,默认时间为1000毫秒,如果在1000毫秒内手指抬起或者手指在屏幕上滑动出了该item,则取消长按定时器,否则就表示可以进行拖拽,手机友好的震动一下,隐藏我们长按的Item,屏幕调用createDragImage()方法来创建我们长按的item的镜像,创建Item的镜像使用的是WindowManager类,该类可以创建一个窗体显示在Activity之上。
再此之前大家先要理解这几个距离,理解这几个距离之前要首先知道getRawX(),getRawY()和getX(),getY()的区别,getRawX(),getRawY()是相对于屏幕的原点的距离,而getX(),getY()是相对于控件左上方的点的距离,为了方便大家理解我用Word简单的画了下图,画得不好,大家将就的看下,红色框框为我们的GridView
-
mPoint2ItemTop 手指按下的点到该Item的上边缘的距离,如上图的1号线
-
mPoint2ItemLeft 手指按下的点到该Item的左边缘的距离,如上图的2号线
-
mOffset2Top GridView的上边缘到屏幕上边缘的距离,如上图的3号线,这个距离包裹状态栏,标题栏,或者一些在GridView上面的布局的高度,这个很重要我们现实Item镜像需要用到
-
mOffset2Left GridView的左边缘到屏幕左边缘的距离,如上图的4号线,我这个Demo的这个距离为0,因为我设置DragGridView的宽度为充满屏幕,但是我们要考虑假如GridView与屏幕左边缘设置了间隙或者左边有其他的布局的情形
-
mDownScrollBorder 这个距离表示当GridView的item过多的时候,手机一屏显示不完全,我们拖动Item镜像到这个高度的时候,GridView自动向下滚动,如上图的5号线
-
.mUpScrollBorder 这个和mDownScrollBorder相反,当我们大于这个高度的时候,GridView自动向上滚动,如上图的6号线
理解了这六个距离,我们就来看看创建Item镜像的方法里面,其他的我不多说,首先设置format为PixelFormat.TRANSLUCENT,表示除了我们显示图片和文字的其他地方为透明,之后就是x,y这两个距离的计算,计算的是item的左上角的坐标,理解了上面这六个距离我们很容易得出x,y的坐标,可是你会发现y的坐标减去了状态栏的高度,这点大家需要注意下,另外我们需要获取item的绘制缓存的Bitmap对象,然后将Bitmap设置到一个ImageView上面,为什么要这么做呢?如果调用addView()方法将item 直接添加到WindowManager里面,会有异常产生,因为item已经有了自己归属的父容器DragGridView,所有我们这里使用一个ImageView来代替item添加到WindowManager里面
上面已经完成了开始拖拽的准备工作,要想拖动镜像我们还需要重写onTouchEvent()方法,获取移动的X,Y的坐标,利用WindowManager的updateViewLayout方法就能对镜像进行拖动,拖动的镜像的时候为了有更好的用户体验,我们还要做item的实时交换效果,我们利用手指移动的X,Y坐标,利用pointToPosition()来获取拖拽到的position,然后将之前的item显示出来,将拖拽到的item进行隐藏,这样子就完成了item在界面上面的交换,但是数据交换我这里没有做,所以我提供了回调接口OnChanageListener,我们只需要自己实现数据的交换逻辑然后刷新DragGridView即可,我们还需要实现DragGridView的自动向上滚动或者向下滚动,使用Handler和mScrollRunnable利用smoothScrollToPositionFromTop()来实现DragGridView滚动,具体的实现大家可以看代码
手指离开界面,将item的镜像移除,并将拖拽到的item显示出来,这样子就实现了GirdView的拖拽效果啦。
好了,今天的讲解就到此结束,效果还不错吧,看完这篇文章你是不是觉得GridView拖拽也不是那么难实现呢?你心里是不是也大概有自己的一个思路,建议大家自己敲敲看看,可以自己去实现下ListView的拖拽实现,ListView比GridView简单些。关于本文的代码,需要进一步理解的话,请加QQ群201055521群共享中查看,我已经贴出了所有的Java代码,注释也很详尽,可以方便理解,实在不懂,还可以回复本公众号或加我的个人微信766136833询问。
最后我们来看看自定义控件的完整代码
- /**
- * 感谢这篇博客的作者,http://blog.csdn.net/xiaanming/article/details/17718579<br>
- * 在这个基础上解决了原作者的问题:Adapter无法使用ViewHolder优化的问题,优化了手势识别率,并添加了trashView功能,
- * 优化自定义控件对外扩展性,解决在上下拉环境下手势冲突问题<br>
- *
- * @author kymjs (https://github.com/kymjs)
- */
- public class KJDragGridView extends GridView {
- private long dragResponseMS = 700; // item长按响应的时间
- private int mDragPosition;// 正在拖拽的position
- private boolean isDrag = false; // 是否可以拖拽,用于控件内部逻辑实现
- private boolean canDrag = true; // 是否可用拖拽,主要用于外部开放设置
- private boolean mAnimationEnd = true;
- private int mDownX;
- private int mDownY;
- private int moveX;
- private int moveY;
- private View mStartDragItemView = null; // 刚开始拖拽的item对应的View
- private ImageView mDragImageView; // 用于拖拽时显示的幻影镜像
- private Bitmap mDragBitmap; // 幻影镜像对应的Bitmap
- private View mTrashView; // 删除item的垃圾桶图标
- private final Vibrator mVibrator; // 震动器
- private final int mStatusHeight;// 状态栏的高度
- private final WindowManager mWindowManager;
- private WindowManager.LayoutParams mWindowLayoutParams; // item镜像的布局参数
- private int mPoint2ItemTop; // 按下的点到所在item的上边缘的距离
- private int mPoint2ItemLeft;
- private int mOffset2Top; // DragGridView距离屏幕顶部的偏移量
- private int mOffset2Left;
- private int mDownScrollBorder; // DragGridView自动向下滚动的边界值
- private int mUpScrollBorder; // DragGridView自动向上滚动的边界值
- private DragGridBaseAdapter mDragAdapter;
- private int mNumColumns;
- private int mColumnWidth;
- private boolean mNumColumnsSet;
- private int mHorizontalSpacing;
- private static final int speed = 20; // DragGridView自动滚动的速度
- private static final int MOVE_OFFSET = 25;
- private boolean moved = false;
- public static final int HANDLE_START = 0x3587;
- public static final int HANDLE_CANCLE = 0x3588;
- public static final int HANDLE_FINISH = 0x3589;
- private static OnMoveListener moveListener; // 拖拽开始与结束监听器
- private OnDeleteListener deleteListener; // 移动到垃圾桶时的监听器
- private final TouchRect moveRect = new TouchRect();
- private final TouchRect gridRect = new TouchRect();
- private final TouchRect trashRect = new TouchRect();
- public KJDragGridView(Context context) {
- this(context, null);
- }
- public KJDragGridView(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
- public KJDragGridView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- mVibrator = (Vibrator) context
- .getSystemService(Context.VIBRATOR_SERVICE);
- mWindowManager = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- mStatusHeight = getStatusHeight(context); // 获取状态栏的高度
- if (!mNumColumnsSet) {
- mNumColumns = AUTO_FIT;
- }
- }
- /**
- * 获取状态栏的高度
- *
- * @param context
- * @return
- */
- private static int getStatusHeight(Context context) {
- int statusHeight = 0;
- Rect localRect = new Rect();
- ((Activity) context).getWindow().getDecorView()
- .getWindowVisibleDisplayFrame(localRect);
- statusHeight = localRect.top;
- if (0 == statusHeight) {
- Class<?> localClass;
- try {
- localClass = Class.forName("com.android.internal.R$dimen");
- Object localObject = localClass.newInstance();
- int i5 = Integer.parseInt(localClass
- .getField("status_bar_height").get(localObject)
- .toString());
- statusHeight = context.getResources().getDimensionPixelSize(i5);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return statusHeight;
- }
- private static final Handler mHandler = new Handler() {
- @Override
- public void handleMessage(android.os.Message msg) {
- if (moveListener != null) {
- if (msg.what == HANDLE_START) {
- moveListener.startMove();
- } else if (msg.what == HANDLE_FINISH) {
- moveListener.finishMove();
- } else if (msg.what == HANDLE_CANCLE) {
- moveListener.cancleMove();
- }
- }
- };
- };
- // 用来处理是否为长按的Runnable
- private final Runnable mLongClickRunnable = new Runnable() {
- @Override
- public void run() {
- if (!canDrag) {
- return;
- }
- isDrag = true; // 设置可以拖拽
- moved = true;
- mHandler.sendEmptyMessage(HANDLE_START);
- mVibrator.vibrate(50); // 震动一下
- mStartDragItemView.setVisibility(View.INVISIBLE);// 隐藏该item
- createDragImage(mDragBitmap, mDownX, mDownY);
- mDragBitmap = null;
- }
- };
- /**
- * 若设置为AUTO_FIT,计算有多少列
- */
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- if (mNumColumns == AUTO_FIT) {
- int numFittedColumns = 1; // 可用列
- if (mColumnWidth > 0) {
- int gridWidth = Math.max(MeasureSpec.getSize(widthMeasureSpec)
- - getPaddingLeft() - getPaddingRight(), 0);
- numFittedColumns = gridWidth / mColumnWidth;
- if (numFittedColumns > 0) {
- while (numFittedColumns != 1) {
- if (numFittedColumns * mColumnWidth
- + (numFittedColumns - 1) * mHorizontalSpacing > gridWidth) {
- numFittedColumns--;
- } else {
- break;
- }
- }
- }
- } else {
- numFittedColumns = 2;
- }
- mNumColumns = numFittedColumns;
- }
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- initRecord();
- }
- /**
- * 初始化坐标数据
- */
- private void initRecord() {
- gridRect.left = this.getLeft();
- gridRect.right = this.getRight();
- gridRect.top = this.getTop();
- gridRect.bottom = this.getBottom();
- if (mTrashView != null) {
- trashRect.left = mTrashView.getLeft();
- trashRect.right = mTrashView.getRight();
- trashRect.bottom = mTrashView.getBottom();
- trashRect.top = mTrashView.getTop();
- }
- }
- /******************** preference method ********************/
- @Override
- public void setAdapter(ListAdapter adapter) {
- super.setAdapter(adapter);
- if (adapter instanceof DragGridBaseAdapter) {
- mDragAdapter = (DragGridBaseAdapter) adapter;
- } else {
- throw new IllegalStateException(
- "the adapter must be implements DragGridAdapter");
- }
- }
- @Override
- public void setNumColumns(int numColumns) {
- super.setNumColumns(numColumns);
- mNumColumnsSet = true;
- this.mNumColumns = numColumns;
- }
- @Override
- public void setColumnWidth(int columnWidth) {
- super.setColumnWidth(columnWidth);
- mColumnWidth = columnWidth;
- }
- @Override
- public void setHorizontalSpacing(int horizontalSpacing) {
- super.setHorizontalSpacing(horizontalSpacing);
- this.mHorizontalSpacing = horizontalSpacing;
- }
- /**
- * 设置响应拖拽的毫秒数,默认是700毫秒
- *
- * @param dragResponseMS
- */
- public void setDragResponseMS(long dragResponseMS) {
- this.dragResponseMS = dragResponseMS;
- }
- public void setOnDeleteListener(OnDeleteListener l) {
- this.deleteListener = l;
- }
- public void setTrashView(View trashView) {
- this.mTrashView = trashView;
- }
- public void setDragEnable(boolean isDrag) {
- this.canDrag = isDrag;
- if (canDrag) {
- mHandler.removeCallbacks(mLongClickRunnable);
- }
- }
- /******************** touch method ********************/
- @Override
- public boolean dispatchTouchEvent(MotionEvent ev) {
- if (canDrag) {
- switch (ev.getAction()) {
- case MotionEvent.ACTION_DOWN:
- mDownX = (int) ev.getX();
- mDownY = (int) ev.getY();
- moveRect.left = mDownX - MOVE_OFFSET;
- moveRect.right = mDownX + MOVE_OFFSET;
- moveRect.top = mDownY - MOVE_OFFSET;
- moveRect.bottom = mDownY + MOVE_OFFSET;
- // 根据按下的X,Y坐标获取所点击item的position
- mDragPosition = pointToPosition(mDownX, mDownY);
- if (mDragPosition == AdapterView.INVALID_POSITION) {
- return super.dispatchTouchEvent(ev);
- }
- // 使用Handler延迟dragResponseMS执行mLongClickRunnable
- mHandler.postDelayed(mLongClickRunnable, dragResponseMS);
- // 根据position获取该item所对应的View
- mStartDragItemView = getChildAt(mDragPosition
- - getFirstVisiblePosition());
- mPoint2ItemTop = mDownY - mStartDragItemView.getTop();
- mPoint2ItemLeft = mDownX - mStartDragItemView.getLeft();
- mOffset2Top = (int) (ev.getRawY() - mDownY);
- mOffset2Left = (int) (ev.getRawX() - mDownX);
- // 获取DragGridView自动向上滚动的偏移量,小于这个值,DragGridView向下滚动
- mDownScrollBorder = getHeight() / 5;
- // 大于这个值,DragGridView向上滚动
- mUpScrollBorder = getHeight() * 4 / 5;
- // 开启mDragItemView绘图缓存
- mStartDragItemView.setDrawingCacheEnabled(true);
- // 获取mDragItemView在缓存中的Bitmap对象
- mDragBitmap = Bitmap.createBitmap(mStartDragItemView
- .getDrawingCache());
- // 这一步很关键,释放绘图缓存,避免出现重复的镜像
- mStartDragItemView.destroyDrawingCache();
- break;
- case MotionEvent.ACTION_MOVE:
- // 如果我们在按下的item上面移动,只要不超过item的边界我们就不移除mRunnable
- if (!isTouchInItem(moveRect, ev.getX(), ev.getY())) {
- mHandler.removeCallbacks(mLongClickRunnable);
- }
- break;
- case MotionEvent.ACTION_UP:
- mHandler.removeCallbacks(mScrollRunnable);
- mHandler.removeCallbacks(mLongClickRunnable);
- if (moved && getAdapter().getCount() > 0) {
- mHandler.sendEmptyMessage(HANDLE_FINISH);
- } else {
- mHandler.sendEmptyMessage(HANDLE_CANCLE);
- }
- moved = false;
- break;
- }
- }
- return super.dispatchTouchEvent(ev);
- }
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- if (isDrag && canDrag && mDragImageView != null) {
- switch (ev.getAction()) {
- case MotionEvent.ACTION_DOWN:
- initRecord();
- break;
- case MotionEvent.ACTION_MOVE:
- moveX = (int) ev.getX();
- moveY = (int) ev.getY();
- onDragItem(moveX, moveY);// 拖动item
- if (mTrashView != null) {
- if (inTrash(moveX, moveY)) {
- mTrashView.setScaleX(1.7f);
- mTrashView.setScaleY(1.7f);
- } else {
- mTrashView.setScaleX(1f);
- mTrashView.setScaleY(1f);
- }
- }
- break;
- case MotionEvent.ACTION_UP:
- onStopDrag();
- isDrag = false;
- if (deleteListener != null && inTrash(ev.getX(), ev.getY())) {
- deleteListener.onDelete(mDragPosition);
- }
- break;
- }
- return true;
- }
- return super.onTouchEvent(ev);
- }
- /**
- * 是否点击在GridView的item上面
- *
- * @param itemView
- * @param x
- * @param y
- * @return
- */
- private boolean isTouchInItem(TouchRect moveRect, float x, float y) {
- // 防止手抖的处理,如果是横向在item上移动是没有影响的,
- // 但是纵向由于外层上下拉控件还是会有影响,具体解决请看NoteBookFragment类中的mSwipeRefreshLayout.setOnTouchListener方法
- if (x < moveRect.right && x > moveRect.left && y < moveRect.bottom
- && y > moveRect.top) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * 创建拖动的镜像
- *
- * @param bitmap
- * @param downX
- * 按下的点相对父控件的X坐标
- * @param downY
- * 按下的点相对父控件的X坐标
- */
- private void createDragImage(Bitmap bitmap, int downX, int downY) {
- mWindowLayoutParams = new WindowManager.LayoutParams();
- mWindowLayoutParams.format = PixelFormat.TRANSLUCENT; // 图片之外的其他地方透明
- mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
- mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left;
- mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top
- - mStatusHeight;
- mWindowLayoutParams.alpha = 0.55f; // 透明度
- mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
- mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
- mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
- mDragImageView = new ImageView(getContext());
- mDragImageView.setImageBitmap(bitmap);
- mWindowManager.addView(mDragImageView, mWindowLayoutParams);
- }
- /**
- * 从界面上面移动拖动镜像
- */
- private void removeDragImage() {
- if (mDragImageView != null) {
- mWindowManager.removeView(mDragImageView);
- mDragImageView = null;
- }
- }
- /**
- * 拖动item,在里面实现了item镜像的位置更新,item的相互交换以及GridView的自行滚动
- *
- * @param x
- * @param y
- */
- private void onDragItem(int moveX, int moveY) {
- mWindowLayoutParams.x = moveX - mPoint2ItemLeft + mOffset2Left;
- mWindowLayoutParams.y = moveY - mPoint2ItemTop + mOffset2Top
- - mStatusHeight;
- mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams); // 更新镜像的位置
- onSwapItem(moveX, moveY);
- // GridView自动滚动
- mHandler.post(mScrollRunnable);
- }
- /**
- * 手指当前处于垃圾桶图标上
- *
- * @param x
- * @param y
- * @return
- */
- private boolean inTrash(float x, float y) {
- x += gridRect.left;
- y += gridRect.top;
- if (x > trashRect.left && x < trashRect.right && y > trashRect.top
- && y < trashRect.bottom) {
- if (mHandler != null && mScrollRunnable != null) {
- mHandler.removeCallbacks(mScrollRunnable);
- }
- if (mDragImageView != null) {
- mDragImageView.setScaleX(0.6f);
- mDragImageView.setScaleY(0.6f);
- }
- return true;
- } else {
- if (mDragImageView != null) {
- mDragImageView.setScaleX(1f);
- mDragImageView.setScaleY(1f);
- }
- return false;
- }
- }
- /**
- * 当moveY的值大于向上滚动的边界值,触发GridView自动向上滚动 当moveY的值小于向下滚动的边界值,触发GridView自动向下滚动
- * 否则不进行滚动
- */
- private final Runnable mScrollRunnable = new Runnable() {
- @Override
- public void run() {
- int scrollY;
- if (getFirstVisiblePosition() == 0
- || getLastVisiblePosition() == getCount() - 1) {
- mHandler.removeCallbacks(mScrollRunnable);
- }
- if (moveY > mUpScrollBorder) {
- scrollY = speed;
- mHandler.postDelayed(mScrollRunnable, 25);
- } else if (moveY < mDownScrollBorder) {
- scrollY = -speed;
- mHandler.postDelayed(mScrollRunnable, 25);
- } else {
- scrollY = 0;
- mHandler.removeCallbacks(mScrollRunnable);
- }
- smoothScrollBy(scrollY, 10);
- }
- };
- /**
- * 交换item,并且控制item之间的显示与隐藏效果
- *
- * @param moveX
- * @param moveY
- */
- private void onSwapItem(int moveX, int moveY) {
- // 获取我们手指移动到的那个item的position
- final int tempPosition = pointToPosition(moveX, moveY);
- // 假如tempPosition 改变了并且tempPosition不等于-1,则进行交换
- if (tempPosition != mDragPosition
- && tempPosition != AdapterView.INVALID_POSITION
- && mAnimationEnd) {
- mDragAdapter.reorderItems(mDragPosition, tempPosition);
- mDragAdapter.setHideItem(tempPosition);
- final ViewTreeObserver observer = getViewTreeObserver();
- observer.addOnPreDrawListener(new OnPreDrawListener() {
- @Override
- public boolean onPreDraw() {
- observer.removeOnPreDrawListener(this);
- animateReorder(mDragPosition, tempPosition);
- mDragPosition = tempPosition;
- return true;
- }
- });
- }
- }
- /**
- * 创建移动动画
- *
- * @param view
- * @param startX
- * @param endX
- * @param startY
- * @param endY
- * @return
- */
- private AnimatorSet createTranslationAnimations(View view, float startX,
- float endX, float startY, float endY) {
- ObjectAnimator animX = ObjectAnimator.ofFloat(view, "translationX",
- startX, endX);
- ObjectAnimator animY = ObjectAnimator.ofFloat(view, "translationY",
- startY, endY);
- AnimatorSet animSetXY = new AnimatorSet();
- animSetXY.playTogether(animX, animY);
- return animSetXY;
- }
- /**
- * item的交换动画效果
- *
- * @param oldPosition
- * @param newPosition
- */
- private void animateReorder(final int oldPosition, final int newPosition) {
- boolean isForward = newPosition > oldPosition;
- List<Animator> resultList = new LinkedList<Animator>();
- if (isForward) {
- for (int pos = oldPosition; pos < newPosition; pos++) {
- View view = getChildAt(pos - getFirstVisiblePosition());
- if (view == null) {
- continue;
- }
- if ((pos + 1) % mNumColumns == 0) {
- resultList.add(createTranslationAnimations(view,
- -view.getWidth() * (mNumColumns - 1), 0,
- view.getHeight(), 0));
- } else {
- resultList.add(createTranslationAnimations(view,
- view.getWidth(), 0, 0, 0));
- }
- }
- } else {
- for (int pos = oldPosition; pos > newPosition; pos--) {
- View view = getChildAt(pos - getFirstVisiblePosition());
- if ((pos + mNumColumns) % mNumColumns == 0) {
- resultList.add(createTranslationAnimations(view,
- view.getWidth() * (mNumColumns - 1), 0,
- -view.getHeight(), 0));
- } else {
- resultList.add(createTranslationAnimations(view,
- -view.getWidth(), 0, 0, 0));
- }
- }
- }
- AnimatorSet resultSet = new AnimatorSet();
- resultSet.playTogether(resultList);
- resultSet.setDuration(300);
- resultSet.setInterpolator(new AccelerateDecelerateInterpolator());
- resultSet.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationStart(Animator animation) {
- mAnimationEnd = false;
- }
- @Override
- public void onAnimationEnd(Animator animation) {
- mAnimationEnd = true;
- }
- });
- resultSet.start();
- }
- /**
- * 停止拖拽我们将之前隐藏的item显示出来,并将镜像移除
- */
- private void onStopDrag() {
- View view = getChildAt(mDragPosition - getFirstVisiblePosition());
- if (view != null) {
- view.setVisibility(View.VISIBLE);
- }
- mDragAdapter.setHideItem(-1);
- removeDragImage();
- if (mTrashView != null) {
- mTrashView.setScaleX(1f);
- mTrashView.setScaleY(1f);
- }
- }
- public void setOnMoveListener(OnMoveListener l) {
- moveListener = l;
- }
- public interface OnMoveListener {
- void startMove();
- void finishMove();
- void cancleMove();
- }
- public interface OnDeleteListener {
- void onDelete(int position);
- }
- public interface DragGridBaseAdapter {
- /**
- * 移动时回调
- */
- public void reorderItems(int oldPosition, int newPosition);
- /**
- * 隐藏时回调
- */
- public void setHideItem(int hidePosition);
- }
- private class TouchRect {
- int top;
- int bottom;
- int left;
- int right;
- }
- }