开发者

android scroll while drag & drop

Hi I am trying to do a drag and drop on a ListView. It works great. But I lost the ability to click and scroll. How to I retain those two? I was thinkng the drag and drop should happen on long press of the item instead of a normal press. Here is my onTouch that is located in the MyListView that extends ListView

@Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        final int x = (int) ev.getX();
        final int y = (int) ev.getY();  

        if (action == MotionEvent.ACTION_DOWN && x < this.getWidth()/4) {
            this._dragMode = true;
        }

        if (!this._isDragNDrop) 
            return super.onTouchEvent(ev);

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                this._startPosition = pointToPosition(x,y);
                if (this._startPosition != INVALID_POSITION) {
                    int mItemPosition = this._startPosition - getFirstVisiblePosition();
                    this._dragPointOffset = y - getChildAt(mItemPosition).getTop();
                    this._dragPointOffset -= ((int)ev.getRawY()) - y;
                    startDrag(mItemPosition,y);
                    drag(x,y);
                }   
                break;
            case MotionEvent.ACTION_MOVE:
                drag(x,y);
                break;
            case MotionEvent.ACTION_CANCEL:
           开发者_如何学Go case MotionEvent.ACTION_UP:
            default:
                this._dragMode = false;
                //_isDragNDrop = false;
                this._endPosition = pointToPosition(x,y);
                stopDrag(this._startPosition - getFirstVisiblePosition());
                if (this._dropListener != null && this._startPosition != INVALID_POSITION && this._endPosition != INVALID_POSITION) 
                    this._dropListener.onDrop(this._startPosition, this._endPosition);
                break;
        }
        return true;
    }


I just implemented drag and drop list view in my application, the dragging starts by long press on an item.

Source code is on GitHub: DraggableListView, I have a blog post to describe it. Hope it helps you.


I'm implementing something similiar. Hopefully this will help someone else as I'm still ironing out the kinks.

...
thumb.setOnDragListener(new Drag());
...

public class Drag implements OnDragListener{
public static int PositionOfDraggedItem = -1;
      public int PositionOfItemDraggedOver = -1;

public Drag() {}

@Override
public boolean onDrag(View v, DragEvent event)
{
    final int action = event.getAction();
    boolean state = true;

    View root = v.getRootView();
    ListView List = (ListView) root.findViewById(android.R.id.list);
    Object holder = v.getTag() instanceof OrderHolder? (OrderHolder)v.getTag() : v.getTag();

    String BookId = holder instanceof OrderHolder? String.valueOf(((OrderHolder)holder).id) : (String)holder;

    switch(action)
    {
        case DragEvent.ACTION_DRAG_STARTED:

            break;
        case DragEvent.ACTION_DRAG_ENTERED:
            if( PositionOfDraggedItem != -1 )
            {
                if( this.PositionOfItemDraggedOver != PositionOfDraggedItem )
                {
                    if( v.getBackground() != null )
                        v.setBackgroundDrawable(v.getContext().getResources().getDrawable(drawable.row_ovr));
                }
            }
            break;
        case DragEvent.ACTION_DRAG_LOCATION:
            /**
             * Set the item being
             * here, as it will not
             * provide location data
             * anywhere else
             */
            if( PositionOfDraggedItem == -1 )
                PositionOfDraggedItem = List.getPositionForView(v);

            /**
             * Set the view thats
             * being dragged over
             */
            this.PositionOfItemDraggedOver = List.getPositionForView(v);

            int PositionOfLastVisibleView = List.getLastVisiblePosition();
            int PositionOfFirstVisibleView = List.getFirstVisiblePosition();

            if( this.PositionOfItemDraggedOver != -1 && ( this.PositionOfItemDraggedOver != PositionOfDraggedItem ) ){
                if( this.PositionOfItemDraggedOver == PositionOfLastVisibleView-1 || this.PositionOfItemDraggedOver == PositionOfLastVisibleView || this.PositionOfItemDraggedOver == PositionOfLastVisibleView+1 ){
                    List.smoothScrollToPosition(PositionOfLastVisibleView+1);
                }else if( this.PositionOfItemDraggedOver == PositionOfFirstVisibleView-1 || this.PositionOfItemDraggedOver == PositionOfFirstVisibleView+1 || this.PositionOfItemDraggedOver == PositionOfFirstVisibleView ){
                    List.smoothScrollToPosition(PositionOfFirstVisibleView-1);
                }
            }
            break;
        case DragEvent.ACTION_DRAG_EXITED:
            if( v.getBackground() != null )
                v.setBackgroundDrawable(v.getContext().getResources().getDrawable(drawable.row));
            break;
        case DragEvent.ACTION_DROP:
            if(event != null)
            {
                ClipData data = event.getClipData();
                if( data != null && data.getItemCount() > 0 )
                {
                    if( !data.getItemAt(0).getText().toString().equalsIgnoreCase(BookId) )
                    {
                        if( v.getBackground() != null )
                            v.setBackgroundDrawable(v.getContext().getResources().getDrawable(drawable.row));
                        /**
                         * Ordering info for
                         * book being dragged
                         */
                        String oShelfOrder = BookManager.item(v.getContext().getContentResolver(), dbhelper.BOOKS_SHELFORDER, 
                                booksprovider.GetUri(dbhelper.BOOKS), Long.parseLong(data.getItemAt(0).getText().toString()));
                        String oBookOrder = BookManager.item(v.getContext().getContentResolver(), dbhelper.BOOKS_BOOKSORDER, 
                                booksprovider.GetUri(dbhelper.BOOKS), Long.parseLong(data.getItemAt(0).getText().toString()));

                        /**
                         * Ordering info
                         * for book being dragged
                         * to
                         */
                        String dShelfOrder = BookManager.item(v.getContext().getContentResolver(), dbhelper.BOOKS_SHELFORDER, 
                                booksprovider.GetUri(dbhelper.BOOKS), Long.parseLong(BookId));
                        String dBookOrder = BookManager.item(v.getContext().getContentResolver(), dbhelper.BOOKS_BOOKSORDER, 
                                booksprovider.GetUri(dbhelper.BOOKS), Long.parseLong(BookId));

                        /**
                         * Update book being dragged
                         */
                        ContentValues args = new ContentValues();
                        args.put(dbhelper.BOOKS_SHELFORDER, dShelfOrder);
                        args.put(dbhelper.BOOKS_BOOKSORDER, dBookOrder);
                        BookManager.updateBook(v.getContext().getContentResolver(), data.getItemAt(0).getText().toString(), args);

                        /**
                         * Update book being dragged to
                         */
                        ContentValues values = new ContentValues();
                        values.put(dbhelper.BOOKS_SHELFORDER, oShelfOrder);
                        values.put(dbhelper.BOOKS_BOOKSORDER, oBookOrder);
                        BookManager.updateBook(v.getContext().getContentResolver(), BookId, values);

                        if( v.getContext() instanceof OrderBooks ){
                            ((OrderBooks)v.getContext()).adapter.refresh();
                            ((OrderBooks)v.getContext()).adapter.notifyDataSetChanged();

                            PositionOfDraggedItem = -1;
                        }
                    }
                }
            }
            break;
        case DragEvent.ACTION_DRAG_ENDED:
            if( event != null && event.getResult())
            {
                v.invalidate();
            }
            break;
    }
    return state;
}

}

Haven't worked on it in awhile, updated to reflect latest changes.


Check out this question for additional help. I also have a component called DragSortListView that I've spent a long time refining. You can find it here:

  • https://github.com/bauerca/drag-sort-listview

I could help you integrate long-press initiated dragging in a fork of my above repo.


I implemented this solution which works for me. The following method is in my Activity and it is called in my dragEventListener when the dragEvent is ACTION_DRAG_ENTERED. Some attributes I declared:

//first visible item (getFirstVisiblePosition() does not work for me)
int firstVisible;
//number of scrolls
int nbrScroll;
//my listview to scroll
ListView mListView;
//the adapter of my listview
SimpleAdapter mAdapter;

...

public void scrollDrag(int position) {
            //this is the position of the item in my listview
            //to scroll down
            //test if the item entered is the last visible
    if (position == mListView.getLastVisiblePosition()
            && id < mListView.getCount()) {
        mAdapter.notifyDataSetChanged();
        mRightDrawerList.post(new Runnable() {
            @Override
            public void run() {
                //scroll down
                mListView.smoothScrollToPosition(mListView
                        .getLastVisiblePosition() + 1);
                firstVisible++;
            }
        });
            //to scroll up
            //test if the item entered is the first visible
    } else if (position == firstVisible && position !=0) {
        mAdapter.notifyDataSetChanged();
        mListView.post(new Runnable() {
            @Override
            public void run() {
                //scroll up
                mListView.smoothScrollToPosition(firstVisible-1);
                firstVisible --;
            }
        });
    }
}

Hope it will help someone.


In Kotlin:

holder.mView.setOnDragListener { v, event ->
    when (event.action) {
        DragEvent.ACTION_DRAG_ENTERED -> {
            ...
        }
        DragEvent.ACTION_DRAG_EXITED, DragEvent.ACTION_DRAG_ENDED -> {
            ...
            val y = calculateY(holder.mView)
            val minY = calculateY(scroll_view) + 200

            val scrollBounds = Rect() 
            scroll_view.getHitRect(scrollBounds) //TODO: calculate only once

            val maxY = minY + scrollBounds.height() - 400
            if (y < minY) {
                scroll_view?.post {
                    scroll_view.smoothScrollBy(0, -200)
                }
            } else if (y > maxY) {
                scroll_view?.post {
                    scroll_view.smoothScrollBy(0, +200)
                }
            }
        }
    }
}


He guys I have made little bit change in rickey's code and it's work for me.

if (PositionOfItemDraggedOver == PositionOfLastVisibleView)
    order_item_list_lv.smoothScrollToPosition(PositionOfLastVisibleView + 1);

if (PositionOfItemDraggedOver == PositionOfFirstVisibleView)
   order_item_list_lv.smoothScrollToPosition(PositionOfFirstVisibleView - 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜