聊聊GridView實現拖拽排序及數據交互的問題
在研究項目中的一個效果的時候,查找資料過程中發現有人有這麼一種需求,就是GridView在實現拖拽排序的基礎上,如果是兩個GridView之間實現拖拽效果,並要實現數據交互。
一、效果圖:
實現這個效果需要考慮的事情:
① 這個UI整體的構建以及事件的傳遞
② 如何實現View的共享,穿過邊界
二、實現思路:
對於單個GridView的拖拽效果實現是參考網上的一篇文章,很抱歉沒能及時保存地址,所以這裡就不貼瞭。
整體實現: 一個容器(DragChessView)裡放置兩個DragView(可拖拽排序Item的View),事件全部交給DragChessView去處理,然後由他去控制事件的分配和處理。在這個容器中還在這兩個DragView上面覆蓋一層FrameLayout,來放置要移動的那個View,然後根據手勢去移動View。DragView裡面進行View的動態交換以及數據交換。
三、實現代碼:
1. DragChessView代碼
public class DragChessView extends FrameLayout { private GestureDetector detector; /** * 點擊拖動 */ public static final int DRAG_WHEN_TOUCH = 0; /** * 長按拖動 */ public static final int DRAG_BY_LONG_CLICK = 1; private int mDragMode = DRAG_WHEN_TOUCH; private boolean hasSendDragMsg = false; private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 0x123: // 啟動拖拽模式 isDragable = true; // 根據點擊的位置生成該位置上的view鏡像 if (isTouchInTop(msg.arg2)) { mDragTop.setCurrentDragPosition(msg.arg1); copyView(mDragTop); } else { mDragBottom.setCurrentDragPosition(msg.arg1); copyView(mDragBottom); } hasSendDragMsg = false; break; default: break; } return false; } }); private boolean isDragable = true; private float[] lastLocation = null; private View mCopyView; private OnTouchListener l; // 轉交給GridView一些常用監聽器 private AdapterView.OnItemLongClickListener itemLongClickListener; private int mTouchArea = 0; private View dragSlider; private Point mMovePoint; // 記錄移動走向,上到下,還是下到上 /** * @param itemClickListener * @描述:item 轉交給gridview一些常用監聽器 */ public void setOnItemClickListener(AdapterView.OnItemClickListener itemClickListener) { mDragBottom.setOnItemClickListener(itemClickListener); } /** * 長按監聽器自己觸發,點擊拖動模式不存在長按 * * @param */ public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener itemLongClickListener) { this.itemLongClickListener = itemLongClickListener; } private boolean canAddViewWhenDragChange = true; private int mStartPoint; private int START_DRAG_TOP = 0; private int START_DRAG_BOTTOM = 1; /** * 手勢監聽器,滾動和單擊 */ private GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (hasSendDragMsg) { hasSendDragMsg = false; handler.removeMessages(0x123); } if (isDragable && mCopyView != null) { if (lastLocation == null && e1 != null) { lastLocation = new float[]{e1.getRawX(), e1.getRawY()}; } if (lastLocation == null) lastLocation = new float[]{0, 0}; distanceX = lastLocation[0] - e2.getRawX(); distanceY = lastLocation[1] - e2.getRawY(); lastLocation[0] = e2.getRawX(); lastLocation[1] = e2.getRawY(); mCopyView.setX(mCopyView.getX() - distanceX); mCopyView.setY(mCopyView.getY() - distanceY); int to = eventToPosition(e2); mCopyView.invalidate(); if (isDragInTop()) { if (isDragFromBottom()) { if (isDragBack(isDragInTop())) { //針對已經進入bottom區域,但是又返回來的情況 mStartPoint = START_DRAG_BOTTOM; //切換,保證移動過程中隻執行一次 canAddViewWhenDragChange = true; } if (canAddViewWhenDragChange) {// 保證移動過程中,數據隻有一次的添加 mDragTop.addSwapView(mDragBottom.getSwapData()); mDragBottom.removeSwapView(); canAddViewWhenDragChange = false; if (hideView != null) hideView.setVisibility(VISIBLE); } if (mDragTop.isViewInitDone()) { mDragTop.setCurrentDragPosition(mDragTop.getGridChildCount() - 1); hideView = mDragTop.getGridChildAt(mDragTop.getCurrentDragPosition()); if (hideView != null) hideView.setVisibility(INVISIBLE); mMovePoint = getDragViewCenterPoint(mDragTop); } } if (mDragTop.isViewInitDone()) dragChangePosition(mDragTop, to); } else { if (isDragFromTop()) { if (isDragBack(isDragInTop())) { mStartPoint = START_DRAG_TOP; canAddViewWhenDragChange = true; } if (canAddViewWhenDragChange) { mDragBottom.addSwapView(mDragTop.getSwapData()); mDragTop.removeSwapView(); canAddViewWhenDragChange = false; if (hideView != null) hideView.setVisibility(VISIBLE); } if (mDragBottom.isViewInitDone()) { mDragBottom.setCurrentDragPosition(mDragBottom.getGridChildCount() - 1); hideView = mDragBottom.getGridChildAt(mDragBottom.getCurrentDragPosition()); if (hideView != null) hideView.setVisibility(INVISIBLE); Log.e("mMovePoint", mMovePoint.x + "-----------" + mMovePoint.y); mMovePoint = getDragViewCenterPoint(mDragBottom); } } if (mDragBottom.isViewInitDone()) dragChangePosition(mDragBottom, to); } } return true; } @Override public void onShowPress(MotionEvent e) { /** 響應長按拖拽 */ if (mDragMode == DRAG_BY_LONG_CLICK) { // 啟動拖拽模式 // isDragable = true; // 通知父控件不攔截我的事件 getParent().requestDisallowInterceptTouchEvent(true); // 根據點擊的位置生成該位置上的view鏡像 int position = eventToPosition(e); if (isCanDragMove(isTouchInTop(e) ? mDragTop : mDragBottom, position)) { // copyView(currentDragPosition = position); Message msg = handler.obtainMessage(0x123, position, (int) e.getY()); // showpress本身大概需要170毫秒 handler.sendMessageDelayed(msg, dragLongPressTime - 170); mMovePoint = new Point((int) e.getX(), (int) e.getY()); mStartPoint = isTouchInTop(e) ? START_DRAG_TOP : START_DRAG_BOTTOM; hasSendDragMsg = true; } } } }; private boolean isDragBack(boolean dragInTop) { return (dragInTop && mStartPoint == START_DRAG_TOP) || (!dragInTop && mStartPoint == START_DRAG_BOTTOM); } private boolean isDragFromTop() { if (mMovePoint != null && mDragTop != null) { if ((mMovePoint.x > mDragTop.getX() && mMovePoint.x < (mDragTop.getX() + mDragTop.getWidth())) && (mMovePoint.y > mDragTop.getY() && mMovePoint.y < (mDragTop.getY() + mDragTop.getHeight()))) { return true; } } return false; } private Point getDragViewCenterPoint(DragView dragView) { Point result = new Point(); if (dragView != null) { int height = dragView.getHeight(); int width = dragView.getWidth(); float x = dragView.getX(); float y = dragView.getY(); result.set((int) (x + width / 2), (int) (y + height / 2)); } return result; } private boolean isDragFromBottom() { if (mMovePoint != null && mDragBottom != null) { if ((mMovePoint.x > mDragBottom.getX() && mMovePoint.x < (mDragBottom.getX() + mDragBottom.getWidth())) && (mMovePoint.y > mDragBottom.getY() && mMovePoint.y < (mDragBottom.getY() + mDragBottom.getHeight()))) { return true; } } return false; } private boolean isTouchInTop(MotionEvent event) { float y = event.getY(); return isTouchInTop(y); } private boolean isTouchInTop(float y) { return y > mDragTop.getY() && y < (mDragTop.getY() + mDragTop.getHeight()); } private void dragChangePosition(DragView dragView, int to) { if (to != dragView.getCurrentDragPosition() && isCanDragMove(dragView, to)) { dragView.onDragPositionChange(dragView.getCurrentDragPosition(), to); } } private boolean isCanDragMove(DragView dragView, int position) { return position >= dragView.getHeadDragPosition() && position < dragView.getGridChildCount() - dragView.getFootDragPosition(); } private FrameLayout mDragFrame; private DragView mDragBottom; private DragView mDragTop; private View hideView; private long dragLongPressTime = 600; public DragChessView(@NonNull Context context) { this(context, null); } public DragChessView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, -1); } public DragChessView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { Context context = getContext(); detector = new GestureDetector(context, simpleOnGestureListener); detector.setIsLongpressEnabled(false); mDragFrame = new FrameLayout(context); dragSlider = LayoutInflater.from(context).inflate(R.layout.layout_drag_chess, this, false); mDragTop = dragSlider.findViewById(R.id.drag_top); mDragBottom = dragSlider.findViewById(R.id.drag_bottom); addView(dragSlider, -1, -1); addView(mDragFrame, -1, -1); } @Override public boolean onTouchEvent(MotionEvent ev) { if (l != null) { l.onTouch(this, ev); } if (!isViewInitDone()) { return false; } if (isDragable) { handleScrollAndCreMirror(ev); } else { // 交給子控件自己處理 dispatchEvent(isTouchInTop(ev) ? mDragTop : mDragBottom, ev); } // 處理拖動 detector.onTouchEvent(ev); if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) { lastLocation = null; if (hasSendDragMsg) { hasSendDragMsg = false; handler.removeMessages(0x123); } } return true; } private void dispatchEvent(DragView dragView, MotionEvent ev) { dragView.dispatchEvent(ev); } private boolean isDragInTop() { if (mCopyView == null) return false; return (mCopyView.getY() + mCopyView.getHeight()) < (mDragTop.getY() + mDragTop.getBottom()); } /** * Description :攔截所有事件 */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } /** * 處理自動滾屏,和單擊生成鏡像 */ private void handleScrollAndCreMirror(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // 通知父控件不攔截我的事件 getParent().requestDisallowInterceptTouchEvent(true); // 根據點擊的位置生成該位置上的view鏡像 int position = eventToPosition(ev); makeCopyView(isTouchInTop(ev) ? mDragTop : mDragBottom, position); break; case MotionEvent.ACTION_MOVE: getParent().requestDisallowInterceptTouchEvent(true);// 通知父控件不攔截我的事件 // 內容太多時,移動到邊緣會自動滾動 decodeScrollArea(isDragInTop() ? mDragTop : mDragBottom, ev); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (hideView != null) { hideView.setVisibility(View.VISIBLE); if (onDragSelectListener != null) { onDragSelectListener.onPutDown(hideView); } } mDragFrame.removeAllViews(); // mDragFrame.scrollTo(0, 0); // isNotifyByDragSort = true; updateUI(isDragInTop() ? mDragTop : mDragBottom, ev); mCopyView = null; canAddViewWhenDragChange = true; // 放手時取消拖動排序模式 if (mDragMode == DRAG_BY_LONG_CLICK) { isDragable = false; } break; default: break; } } private void updateUI(DragView dragView, MotionEvent ev) { if (dragView.isHasPositionChange()) { dragView.setHasPositionChange(false); dragView.getAdapter().notifyDataSetChanged(); } else if (mDragMode == DRAG_BY_LONG_CLICK && itemLongClickListener != null) { dragView.onItemLongClick(itemLongClickListener); } // 停止滾動 if (dragView.isCanScroll()) { int scrollStates2 = dragView.decodeTouchArea(ev); if (scrollStates2 != 0) { dragView.onTouchAreaChange(0); mTouchArea = 0; } } } private void decodeScrollArea(DragView dragView, MotionEvent ev) { if (dragView.isCanScroll()) { int touchArea = dragView.decodeTouchArea(ev); if (touchArea != mTouchArea) { dragView.onTouchAreaChange(touchArea); mTouchArea = touchArea; } } } private void makeCopyView(DragView dragView, int position) { if (position >= dragView.getHeadDragPosition() && position < dragView.getGridChildCount() - dragView.getFootDragPosition()) { dragView.setCurrentDragPosition(position); copyView(dragView); } } /** * 得到事件觸發點, 摸到的是哪一個item */ public int eventToPosition(MotionEvent ev) { if (ev != null) { if (isTouchInTop(ev)) return mDragTop.eventToPosition(ev); return mDragBottom.eventToPosition(ev); } return 0; } /** * 復制一個鏡像,並添加到透明層 */ private void copyView(DragView dragView) { // TODO: 2018/4/2 創建可移動的 item hideView = dragView.getGridChildAt(dragView.getCurrentDragPosition()); int realPosition = dragView.getGridChildPos(hideView); DragAdapter adapter = dragView.getAdapter(); if (!adapter.isUseCopyView()) { mCopyView = adapter.getView(realPosition, mCopyView, mDragFrame); } else { mCopyView = adapter.copyView(realPosition, mCopyView, mDragFrame); } hideView.setVisibility(View.INVISIBLE); if (mCopyView.getParent() == null) mDragFrame.addView(mCopyView, dragView.getmColWidth(), dragView.getmColHeight()); int[] l1 = new int[2]; int[] l2 = new int[2]; hideView.getLocationOnScreen(l1); mDragFrame.getLocationOnScreen(l2); // mCopyView.setX(hideView.getLeft()); // mCopyView.setY(hideView.getTop() - mCurrentY); mCopyView.setX(l1[0] - l2[0]); mCopyView.setY(l1[1] - l2[1]); if (onDragSelectListener == null) { mCopyView.setScaleX(1.2f); mCopyView.setScaleY(1.2f); } else { onDragSelectListener.onDragSelect(mCopyView); } } private DragSortGridView.OnDragSelectListener onDragSelectListener; /** * @描述:一個item view剛被拖拽和放下時起來生成鏡像時調用. */ public void setOnDragSelectListener(DragSortGridView.OnDragSelectListener onDragSelectListener) { this.onDragSelectListener = onDragSelectListener; } /** * @param mode int類型 * @描述:設置拖動的策略是點擊還是長按 */ public void setDragModel(int mode) { this.mDragMode = mode; isDragable = mode == DRAG_WHEN_TOUCH; } public void setAnimFrame(ListenFrameLayout mDragFrame) { this.mDragFrame = mDragFrame; } /** * 設置長按需要用時 * * @param time */ public void setDragLongPressTime(long time) { dragLongPressTime = time; } public void setBottomAdapter(@NotNull DragAdapter adapter) { mDragBottom.setAdapter(adapter); } public boolean isViewInitDone() { boolean result = mDragBottom.isViewInitDone(); if (mDragTop.getVisibility() == VISIBLE) result &= mDragTop.isViewInitDone(); return result; } public void setTopAdapter(@NotNull DragAdapter adapter) { mDragTop.setAdapter(adapter); } }
2. DragView的實現:
public class DragView<T> extends FrameLayout { private static final int TAG_KEY = R.id.first; private NoScrollGridView mGridView; private List<View> mChilds = new ArrayList<View>(); protected int mNumColumns = 3; protected int mColHeight = 0; protected int mColWidth = 0; protected int mChildCount = 0; protected int mMaxHeight = 0; private boolean isViewInitDone = false; private ListenScrollView mScrollView; private int mCurrentY = 0; /** * 自動滾屏的動畫 */ private ValueAnimator animator; private DragAdapter adapter; private int headDragPosition = 0; private int footDragPosition = 0; private int currentDragPosition = -1; /** * 是否有位置發生改變,否則不用重繪 */ private boolean hasPositionChange = false; /** * gridview能否滾動,是否內容太多 */ private boolean canScroll = true; /** * 動畫時間 */ private static final long ANIM_DURING = 250; private Object swapeData; public DragView(@NonNull Context context) { this(context, null); } public DragView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, -1); } public DragView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { Context context = getContext(); mGridView = new NoScrollGridView(context); mGridView.setVerticalScrollBarEnabled(false); mGridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); mGridView.setSelector(new ColorDrawable()); // View的寬高之類必須在測量,佈局,繪制一系列過程之後才能獲取到 mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (mChilds.isEmpty()) { for (int i = 0; i < mGridView.getChildCount(); i++) { View view = mGridView.getChildAt(i); view.setTag(TAG_KEY, new int[]{0, 0}); view.clearAnimation(); mChilds.add(view); } } if (!mChilds.isEmpty()) { mColHeight = mChilds.get(0).getHeight(); } mColWidth = mGridView.getColumnWidth(); if (mChildCount % mNumColumns == 0) { mMaxHeight = mColHeight * mChildCount / mNumColumns; } else { mMaxHeight = mColHeight * (mChildCount / mNumColumns + 1); } canScroll = mMaxHeight - getHeight() > 0; // 告知事件處理,完成View加載,許多屬性也已經初始化瞭 isViewInitDone = true; } }); mScrollView = new ListenScrollView(context); mGridView.setNumColumns(mNumColumns); mScrollView.addView(mGridView, -1, -1); addView(mScrollView, -1, -1); } private DataSetObserver observer = new DataSetObserver() { @Override public void onChanged() { mChildCount = adapter.getCount(); // 下列屬性狀態清除,才會在被調用notifyDataSetChange時,在gridview測量佈局完成後重新獲取 mChilds.clear(); mColHeight = mColWidth = mMaxHeight = 0; isViewInitDone = false; } @Override public void onInvalidated() { mChildCount = adapter.getCount(); } }; /** * 控制自動滾屏的動畫監聽器. */ private ValueAnimator.AnimatorUpdateListener animUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int targetY = Math.round((Float) animation.getAnimatedValue()); if (targetY < 0) { targetY = 0; } else if (targetY > mMaxHeight - getHeight()) { targetY = mMaxHeight - getHeight(); } // mGridView.scrollTo(0, targetY); mScrollView.smoothScrollTo(0, targetY); // mCurrentY = targetY; } }; public void setAdapter(DragAdapter adapter) { if (this.adapter != null && observer != null) { this.adapter.unregisterDataSetObserver(observer); } this.adapter = adapter; mGridView.setAdapter(adapter); adapter.registerDataSetObserver(observer); mChildCount = adapter.getCount(); } /** * @param from * @param to * @描述:動畫效果移動View */ public void translateView(int from, int to) { View view = mChilds.get(from); int fromXValue = ((int[]) view.getTag(TAG_KEY))[0]; int fromYValue = ((int[]) view.getTag(TAG_KEY))[1]; int toXValue = to % mNumColumns - from % mNumColumns + fromXValue; int toYValue = to / mNumColumns - from / mNumColumns + fromYValue; Animation animation = new TranslateAnimation(1, fromXValue, 1, toXValue, 1, fromYValue, 1, toYValue); animation.setDuration(ANIM_DURING); animation.setFillAfter(true); view.setTag(TAG_KEY, new int[]{toXValue, toYValue}); view.startAnimation(animation); } /** * @param from * @param to * @描述:拖動View使位置發生改變時 */ public void onDragPositionChange(int from, int to) { if (from > to) { for (int i = to; i < from; i++) { translateView(i, i + 1); } } else { for (int i = to; i > from; i--) { translateView(i, i - 1); } } if (!hasPositionChange) { hasPositionChange = true; } if ((from >= mChilds.size() || from < 0) || (to >= mChilds.size() || to < 0)) return; adapter.onDataModelMove(from, to); View view = mChilds.remove(from); mChilds.add(to, view); currentDragPosition = to; } /** * @param scrollStates * @描述:觸摸區域改變,做相應處理,開始滾動或停止滾動 */ public void onTouchAreaChange(int scrollStates) { if (!canScroll) { return; } if (animator != null) { animator.removeUpdateListener(animUpdateListener); } if (scrollStates == 1) {// 從普通區域進入觸發向上滾動的區域 int instance = mMaxHeight - getHeight() - mCurrentY; animator = ValueAnimator.ofFloat(mCurrentY, mMaxHeight - getHeight()); animator.setDuration((long) (instance / 0.5f)); animator.setTarget(mGridView); animator.addUpdateListener(animUpdateListener); animator.start(); } else if (scrollStates == -1) {// 進入觸發向下滾動的區域 animator = ValueAnimator.ofFloat(mCurrentY, 0); animator.setDuration((long) (mCurrentY / 0.5f)); animator.setTarget(mGridView); animator.addUpdateListener(animUpdateListener); animator.start(); } } /** * @param ev 事件 * @return 0中間區域, 1底部,-1頂部 * @描述: 檢查當前觸摸事件位於哪個區域, 頂部1/5可能觸發下滾,底部1/5可能觸發上滾 */ public int decodeTouchArea(MotionEvent ev) { if (ev.getY() > (getHeight() + getY()) * 4 / (double) 5) { return 1; } else if (ev.getY() < (getHeight() + getY()) / (double) 5) { return -1; } else { return 0; } } public boolean isViewInitDone() { return isViewInitDone; } /** * 設置前幾個item不可以改變位置 */ public void setNoPositionChangeItemCount(int count) { headDragPosition = count; } /** * 設置後幾個item不可以改變位置 */ public void setFootNoPositionChangeItemCount(int count) { footDragPosition = count; } public int getHeadDragPosition() { return headDragPosition; } public int getFootDragPosition() { return footDragPosition; } public int getGridChildCount() { return mChilds.size(); } public View getGridChildAt(int position) { if (position < 0 || position >= mChilds.size()) return null; return mChilds.get(position); } public int getGridChildPos(View view) { return mGridView.indexOfChild(view); } public void setCurrentDragPosition(int currentDragPosition) { this.currentDragPosition = currentDragPosition; } public int getCurrentDragPosition() { return currentDragPosition; } public int getmColHeight() { return mColHeight; } public int getmColWidth() { return mColWidth; } public DragAdapter getAdapter() { return adapter; } public boolean isHasPositionChange() { return hasPositionChange; } public void setHasPositionChange(boolean hasPositionChange) { this.hasPositionChange = hasPositionChange; } public boolean isCanScroll() { return canScroll; } public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) { mGridView.setOnItemClickListener(onItemClickListener); } public void onItemLongClick(AdapterView.OnItemLongClickListener itemLongClickListener) { itemLongClickListener.onItemLongClick(mGridView, childAt(currentDragPosition), currentDragPosition, 0); } public View childAt(int index) { return mGridView.getChildAt(index); } public void dispatchEvent(MotionEvent ev) { if (canScroll) mScrollView.dispatchTouchEvent(ev); else mGridView.dispatchTouchEvent(ev); } public int eventToPosition(MotionEvent ev) { if (ev != null) { int m = (int) ev.getX() / mColWidth; int n = (int) (ev.getY() - getY() + mCurrentY) / mColHeight; int position = n * mNumColumns + m; if (position >= mChildCount) { return mChildCount - 1; } else { return position; } } return 0; } public void addSwapView(Object data) { adapter.addNewData(data); } public Object getSwapData() { return adapter.getSwapData(currentDragPosition); } public void removeSwapView() { if (adapter != null) { adapter.removeData(currentDragPosition); adapter.notifyDataSetChanged(); } } class ListenScrollView extends ScrollView { public ListenScrollView(Context context) { super(context); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); mCurrentY = getScrollY(); } } class NoScrollGridView extends GridView { public NoScrollGridView(Context context) { super(context); } /** * @return * @描述:兼容老版本的getColumWidth * @作者 [pWX273343] 2015年7月1日 */ public int getColumnWidth() { return getWidth() / getNumColumns(); } public NoScrollGridView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, mExpandSpec); } } }
3. DragAdapter的代碼:
public abstract class DragAdapter extends BaseAdapter { /** * @param from * @param to * @描述:當從from排序被拖到to排序時的處理方式,請對相應的數據做處理。 */ public abstract void onDataModelMove(int from, int to); /** * 復制View使用的方法,默認直接使用getView方法獲取 * * @param position * @param convertView * @param parent * @return */ public View copyView(int position, View convertView, ViewGroup parent) { return null; } /** * 是否啟用copyView方法 * * @return true 使用copyView復制 false 使用getView直接獲取鏡像 */ public boolean isUseCopyView() { return false; } public abstract Object getSwapData(int position); public abstract void removeData(int position); public void addNewData(Object data) { } }
4.使用MainActivity:
class GridDragShortActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.attributes.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION setContentView(R.layout.activity_grid_drag_short) //長按item響應該item的拖動排序,默認是觸摸就開始拖動 drag_main.setDragModel(DragSortGridView.DRAG_BY_LONG_CLICK) //設置每行個數 // drag_main.numColumns = 3 var arrayList = ArrayList<String>() var list = ArrayList<String>() for (i in 0..29) { arrayList.add("" + i) } for (i in 0..29) { list.add(('A' + i).toString()) } drag_main.setBottomAdapter(CustomAdapter(list, this)) drag_main.setTopAdapter(CustomAdapter(arrayList, this)) } }
佈局:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.mdzz.DragChessView android:id="@+id/drag_main" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </RelativeLayout>
佈局 layout_drag_chess.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.chineseall.bookshelf.mdzz.DragView android:id="@+id/drag_top" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#ffffff" /> <TextView android:id="@+id/folder_title" android:layout_width="match_parent" android:layout_height="40dp" android:background="#0586F9" android:gravity="center" android:text="@string/text" android:textColor="#ffffff" android:textSize="18sp" /> <com.chineseall.bookshelf.mdzz.DragView android:id="@+id/drag_bottom" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#ffffff" /> </LinearLayout>
在實際使用中,可以更據需要再去拓展使用,代碼演變過程中的另一個效果,來看看,以它結束這篇:
到此這篇關於GridView實現拖拽排序以及數據交互的文章就介紹到這瞭,更多相關GridView拖拽排序內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Android實現控件拖動效果
- GridView實現桌面圖標顯示案例
- ViewPager2滑動沖突解決方案
- Android為View添加拖放效果的方法實例
- View事件分發原理和ViewPager+ListView嵌套滑動沖突