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:
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With