1、概述
项目要求一个可拖拽的gridview功能,主要是可以长按图标,然后手指移动到对应位置,松开后图标移动到对应手指松开的位置,后面的图标依次挪移一个position。
2、效果图
3、重写dispatchTouchEvent方法
/** * 长按的Runnable */ private Runnable mLongClickRunable = new Runnable() { @Override public void run() { isDrag = true; //mVibrator.vibrate(200); //隐藏该item mDragView.setVisibility(INVISIBLE); //在点击的地方创建并显示item镜像 createDragView(mDragBitmap, mDownX, mDownY); } }; /** * 当moveY的值大于向上滚动的边界值,触发GridView自动向上滚动 * 当moveY的值小于向下滚动的边界值,触犯GridView自动向下滚动 * 否则不进行滚动 */ private Runnable mScrollRunbale = new Runnable() { @Override public void run() { int scrollY = 0; if (mMoveY > mUpScrollBorder){ scrollY = mSpeed; mHandler.postDelayed(mScrollRunbale,25); }else if (mMoveY < mDownScrollBorder){ scrollY = -mSpeed; mHandler.postDelayed(mScrollRunbale,25); }else { scrollY = 0; mHandler.removeCallbacks(mScrollRunbale); } smoothScrollBy(scrollY,10); } }; 复制代码
5、对外暴露的方法
/************************对外提供的接口***************************************/ public boolean isDrag() { return isDrag; } //设置是否可拖拽 public void setDrag(boolean drag) { isDrag = drag; } public long getDragResponseMs() { return mDragResponseMs; } //设置长按响应时长 public void setDragResponseMs(long mDragResponseMs) { this.mDragResponseMs = mDragResponseMs; } public void setOnItemChangeListener(OnItemChangeListener changeListener) { this.changeListener = changeListener; } /******************************************************************************/ 复制代码
6、如何在页面中调用
DragGridView dragGridView = findViewById(R.id.dgv); dragGridView.setNumColumns(NUM_COLUMNS); initData(); mMoreColorTypeAdapter = new MoreColorTypeAdapter(this, true, data, NUM_COLUMNS); dragGridView.setAdapter(mMoreColorTypeAdapter); dragGridView.setOnItemClickListener(this); dragGridView.setOnItemChangeListener(new DragGridView.OnItemChangeListener() { @Override public void onChange(int from, int to) { Data dataBean = data.get(from); //直接交互 //Collections.swap(dataSourceList,from,to); //非直接交互 这里的处理需要注意下 排序交换 if(from < to){ for(int i = from; i < to; i++){ Collections.swap(data, i, i + 1); } }else if(from > to){ for(int i = from; i > to; i--){ Collections.swap(data, i, i - 1); } } data.set(to, dataBean); mMoreColorTypeAdapter.notifyDataSetChanged(); } @Override public void onStop() { //拖动停止 } }); 复制代码