Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 一個可以拖動的自定義Gridview代碼

一個可以拖動的自定義Gridview代碼

編輯:關於Android編程

這個可以拖動的gridview繼承於gridview,所以,用法和gridview一樣,

代碼如下:

public class DragGridView 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 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 float dragViewScale = 1.3f;

    private final TouchRect moveRect = new TouchRect();
    private final TouchRect gridRect = new TouchRect();
    private final TouchRect trashRect = new TouchRect();

    public DragGridView(Context context) {
        this(context, null);
    }

    public DragGridView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragGridView(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();
    }

    @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 setDragEnable(boolean isDrag) {
        this.canDrag = isDrag;
        if (canDrag) {
            mHandler.removeCallbacks(mLongClickRunnable);
        }
    }


    @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 || mDragPosition == getDragAdapter().getRealCount()) {
                        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
                    break;
                case MotionEvent.ACTION_UP:
                    onStopDrag();
                    isDrag = false;
                    break;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 是否點擊在GridView的item上面
     *
     * @param moveRect
     * @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;
        initDragOffset(bitmap);
        mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left;
        mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top - mStatusHeight;
        mWindowLayoutParams.alpha = 0.618f; // 透明度
        mWindowLayoutParams.width = (int) (bitmap.getWidth() * dragViewScale);
        mWindowLayoutParams.height = (int) (bitmap.getHeight() * dragViewScale);
        mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        mDragImageView = new ImageView(getContext());
        mDragImageView.setScaleType(ImageView.ScaleType.FIT_XY);
        mDragImageView.setImageBitmap(bitmap);
        mWindowManager.addView(mDragImageView, mWindowLayoutParams);
    }

    private void initDragOffset(Bitmap bitmap){
        mOffset2Left = mOffset2Left - (int) (bitmap.getWidth() * (dragViewScale - 1) / 2);
        mOffset2Top = mOffset2Top - (int) (bitmap.getHeight() * (dragViewScale - 1) / 2);
    }

    /**
     * 從界面上面移動拖動鏡像
     */
    private void removeDragImage() {
        if (mDragImageView != null) {
            mWindowManager.removeView(mDragImageView);
            mDragImageView = null;
        }
    }

    /**
     * 拖動item,在裡面實現了item鏡像的位置更新,item的相互交換以及GridView的自行滾動
     *
     * @param moveX
     * @param moveY
     */
    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);
    }


    /**
     * 當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
                && tempPosition != getDragAdapter().getRealCount()
                && 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 resultList = new LinkedList();
        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();
    }

    private DragGridBaseAdapter getDragAdapter() {
        return (DragGridBaseAdapter) getAdapter();
    }

    public void setOnMoveListener(OnMoveListener listener) {
        moveListener = listener;
    }

    public interface OnMoveListener {
        void startMove();

        void finishMove();

        void cancleMove();
    }

    public interface OnDeleteListener {
        void onDelete(int position);
    }

    public interface DragGridBaseAdapter {
        /**
         * 移動時回調
         */
        void reorderItems(int oldPosition, int newPosition);

        /**
         * 隱藏時回調
         */
        void setHideItem(int hidePosition);

        int getRealCount();
    }

    private class TouchRect {
        int top;
        int bottom;
        int left;
        int right;
    }
}


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved