import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import com.easou.search.R;
import com.easou.search.util.Util;
public class DraggableListView extends ListView {
private ImageView mDragView;// 被拖拽项的影像,其实就是一个ImageView
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowParams;
private int mDragPos; // 哪个ITEM被拖动了
private int mFirstDragPos; // where was the dragged item
// originally//手指拖动项原始在列表中的位置
private int mDragPoint; // at what offset inside the item did the user grab
// it//在当前数据项中的位置
private int mCoordOffset; // the difference between screen coordinates and
// coordinates in this
// view//当前视图和屏幕的距离(这里只使用了y方向上)
private DragListener mDragListener;
private DropListener mDropListener;
private RemoveListener mRemoveListener;
private int mUpperBound;
private int mLowerBound;
private int mHeight;
private GestureDetector mGestureDetector;
public static final int FLING = 0;
public static final int SLIDE_RIGHT = 1;
public static final int SLIDE_LEFT = 2;
private int mRemoveMode = -1;
private Rect mTempRect = new Rect();
private Bitmap mDragBitmap;// 拖动的图像
private final int mTouchSlop;// 判断滑动的一个距离
private int mItemHeightNormal = -1;
private int mItemHeightExpanded = -1;
private int grabberId = -1;
private int dragndropBackgroundColor = 0x00000000;
private final float MAP_PADDING_TOP = 6f;// 因为加了阴影,为了对齐,所以要向上移动5*dip
public DraggableListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DraggableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.TouchListView, 0, 0);
mItemHeightNormal = a.getDimensionPixelSize(
R.styleable.TouchListView_normal_height, 0);
mItemHeightExpanded = a.getDimensionPixelSize(
R.styleable.TouchListView_expanded_height,
mItemHeightNormal);
grabberId = a.getResourceId(R.styleable.TouchListView_grabber, -1);
// Log.e("sjj", "grabberId is " + grabberId);
dragndropBackgroundColor = a.getColor(
R.styleable.TouchListView_dragndrop_background, 0x00000000);
mRemoveMode = a.getInt(R.styleable.TouchListView_remove_mode, -1);
a.recycle();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mRemoveListener != null && mGestureDetector == null) {
if (mRemoveMode == FLING) {
mGestureDetector = new GestureDetector(getContext(),
new SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1,
MotionEvent e2, float velocityX,
float velocityY) {
if (mDragView != null) {
if (velocityX > 1000) {
Rect r = mTempRect;
mDragView.getDrawingRect(r);
if (e2.getX() > r.right * 2 / 3) {
// fast fling right with release
// near the right edge of the screen
stopDragging();
mRemoveListener
.remove(mFirstDragPos);
unExpandViews(true);
}
}
// flinging while dragging should have no
// effect
return true;
}
return false;
}
});
}
}
if (mDragListener != null || mDropListener != null) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
this.requestLayout();
this.invalidateViews();
int x = (int) ev.getX();
int y = (int) ev.getY();
int itemnum = pointToPosition(x, y); // 选中的数据项位置
if (itemnum == AdapterView.INVALID_POSITION) {// 如果是无效位置(超出边界,分割线等位置),返回
break;
}
// 获取选中项View
// getChildAt(int position)显示display在界面的position位置的View
// getFirstVisiblePosition()返回第一个display在界面的view在adapter的位置position,可能是0,也可能是4
ViewGroup item = (ViewGroup) getChildAt(itemnum
- getFirstVisiblePosition());
// mDragPoint点击位置在点击View内的相对位置
mDragPoint = y - item.getTop();
// mCoordOffset屏幕位置和当前ListView位置的偏移量,这里只用到y坐标上的值
// 这两个参数用于后面拖动的开始位置和移动位置的计算
mCoordOffset = ((int) ev.getRawY()) - y;
// 获取右边的拖动图标,这个对后面分组拖拽有妙用
View dragger = item.findViewById(grabberId);
Rect r = mTempRect;
// dragger.getDrawingRect(r);
r.left = dragger.getLeft();
r.right = dragger.getRight();
r.top = dragger.getTop();
r.bottom = dragger.getBottom();
if ((r.left < x) && (x < r.right)) {// 如果在拖拽图片区域内则开始拖动吧
item.setDrawingCacheEnabled(true);
// Create a copy of the drawing cache so that it does not
// get recycled
// by the framework when the list tries to clean up memory
Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache());
item.setDrawingCacheEnabled(false);
startDragging(bitmap, y);
mDragPos = itemnum;
mFirstDragPos = mDragPos;
mHeight = getHeight();
int touchSlop = mTouchSlop;
mUpperBound = Math.min(y - touchSlop, mHeight / 3);
mLowerBound = Math.max(y + touchSlop, mHeight * 2 / 3);
return false;
}
mDragView = null;
break;
}
}
return super.onInterceptTouchEvent(ev);
}
/*
* pointToPosition() doesn't consider invisible views, but we need to, so
* implement a slightly different version.
*/
private int myPointToPosition(int x, int y) {
Rect frame = mTempRect;
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
child.getHitRect(frame);
if (frame.contains(frame.left + 3, y)) {
return getFirstVisiblePosition() + i;
}
}
return INVALID_POSITION;
}
private int getItemForPosition(int y) {
int adjustedy = y - mDragPoint - 32;
int pos = myPointToPosition(0, adjustedy);
if (pos >= 0) {
if (pos <= mFirstDragPos) {
pos += 1;
}
} else if (adjustedy < 0) {
pos = 0;
}
return pos;
}
private void adjustScrollBounds(int y) {
if (y >= mHeight / 3) {
mUpperBound = mHeight / 3;
}
if (y <= mHeight * 2 / 3) {
mLowerBound = mHeight * 2 / 3;
}
}
/*
* Restore size and visibility for all listitems
*/
private void unExpandViews(boolean deletion) {
for (int i = 0;; i++) {
View v = getChildAt(i);
if (v == null) {
if (deletion) {
// HACK force update of mItemCount
int position = getFirstVisiblePosition();
int y = getChildAt(0).getTop();
setAdapter(getAdapter());
setSelectionFromTop(position, y);
// end hack
}
layoutChildren(); // force children to be recreated where needed
v = getChildAt(i);
if (v == null) {
break;
}
}
ViewGroup.LayoutParams params = v.getLayoutParams();
params.height = mItemHeightNormal;
v.setLayoutParams(params);
v.setVisibility(View.VISIBLE);
}
}
/*
* Adjust visibility and size to make it appear as though an item is being
* dragged around and other items are making room for it: If dropping the
* item would result in it still being in the same place, then make the
* dragged listitem's size normal, but make the item invisible. Otherwise,
* if the dragged listitem is still on screen, make it as small as possible
* and expand the item below the insert point. If the dragged item is not on
* screen, only expand the item below the current insertpoint.
*/
private void doExpansion() {
int childnum = mDragPos - getFirstVisiblePosition();
if (mDragPos > mFirstDragPos) {
childnum++;
}
View first = getChildAt(mFirstDragPos - getFirstVisiblePosition());
for (int i = 0;; i++) {
View vv = getChildAt(i);
if (vv == null) {
break;
}
int height = mItemHeightNormal;
int visibility = View.VISIBLE;
if (vv.equals(first)) {
// processing the item that is being dragged
if (mDragPos == mFirstDragPos) {
// hovering over the original location
visibility = View.INVISIBLE;
} else {
// not hovering over it
height = 1;
}
} else if (i == childnum) {
if (mDragPos < getCount() - 1) {
height = mItemHeightExpanded;
}
}
ViewGroup.LayoutParams params = vv.getLayoutParams();
params.height = height;
vv.setLayoutParams(params);
vv.setVisibility(visibility);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mGestureDetector != null) {
mGestureDetector.onTouchEvent(ev);
}
if ((mDragListener != null || mDropListener != null)
&& mDragView != null) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Rect r = mTempRect;
mDragView.getDrawingRect(r);
stopDragging();
if (mDropListener != null && mDragPos >= 0
&& mDragPos < getCount()) {
mDropListener.drop(mFirstDragPos, mDragPos);
}
// unExpandViews(false);
break;
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int x = (int) ev.getX();
int y = (int) ev.getY();
dragView(x, y);
int itemnum = getItemForPosition(y);
if (itemnum >= 0) {
if (action == MotionEvent.ACTION_DOWN
|| itemnum != mDragPos) {
if (mDragListener != null) {
mDragListener.drag(mDragPos, itemnum);
}
mDragPos = itemnum;
// doExpansion();
}
int speed = 0;
adjustScrollBounds(y);
if (y > mLowerBound) {
// scroll the list up a bit
speed = y > (mHeight + mLowerBound) / 2 ? 16 : 4;
} else if (y < mUpperBound) {
// scroll the list down a bit
speed = y < mUpperBound / 2 ? -16 : -4;
}
if (speed != 0) {
int ref = pointToPosition(x, y);
// Log.e("ttt", "ref is " + ref);
if (ref == AdapterView.INVALID_POSITION) {
// we hit a divider or an invisible view, check
// somewhere else
ref = pointToPosition(0, mHeight / 2
+ getDividerHeight() + 64);
}
View v = getChildAt(ref - getFirstVisiblePosition());
// Log.e("ttt", "v" + v);
if (v != null) {
int pos = v.getTop();
setSelectionFromTop(ref, pos - speed);
}
}
}
break;
}
return true;
}
return super.onTouchEvent(ev);
}
/**
* 准备开始拖动ITME
*
* @param bm
* @param y
*/
private void startDragging(Bitmap bm, int y) {
stopDragging(); // 释放影像,在准备影像的时候,防止影像没释放,每次都执行一下
mWindowParams = new WindowManager.LayoutParams();
// 从上到下计算y方向上的相对位置,
mWindowParams.gravity = Gravity.TOP;
// 图标的Y坐标
int windowY = y - mDragPoint + mCoordOffset;
mWindowParams.x = 0;
mWindowParams.y = windowY
- (int) (Util.getdensityDpi(this.getContext()) * MAP_PADDING_TOP);// 减去上面阴影部分好对齐
mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
// 下面这些参数能够帮助准确定位到选中项点击位置,照抄即可
mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
mWindowParams.format = PixelFormat.TRANSLUCENT;
mWindowParams.windowAnimations = 0;
ImageView v = new ImageView(getContext());
// int backGroundColor =
// getContext().getResources().getColor(R.color.dragndrop_background);
// v.setBackgroundColor(dragndropBackgroundColor); TODO removed by shijj
// 11-23 15:13
v.setBackgroundDrawable(this.getResources().getDrawable(
R.drawable.bookmark_list_item_drap_bg));
v.setImageBitmap(bm);
mDragBitmap = bm;
mWindowManager = (WindowManager) getContext()
.getSystemService("window");
mWindowManager.addView(v, mWindowParams);
mDragView = v;
}
/**
* 拖动图像
*
* @param x
* @param y
*/
private void dragView(int x, int y) {
float alpha = 1.0f;
int width = mDragView.getWidth();
if (mRemoveMode == SLIDE_RIGHT) {
if (x > width / 2) {
alpha = ((float) (width - x)) / (width / 2);
}
mWindowParams.alpha = alpha;
} else if (mRemoveMode == SLIDE_LEFT) {
if (x < width / 2) {
alpha = ((float) x) / (width / 2);
}
mWindowParams.alpha = 0.8F;// TODO MODIFY BY SHIJJ
// mWindowParams.alpha = alpha;
}
// 图标的Y坐标
int windowY = y - mDragPoint + mCoordOffset;
mWindowParams.y = windowY
- (int) (Util.getdensityDpi(this.getContext()) * MAP_PADDING_TOP);// 减去上面阴影部分好对齐
mWindowManager.updateViewLayout(mDragView, mWindowParams);
// // 为了避免滑动到分割线的时候,返回-1的问题
// int tempPosition = pointToPosition(0, y);
// if (tempPosition != INVALID_POSITION) {
// dragPosition = tempPosition;
// }
// // 滚动
// int scrollHeight = 0;
// if (y < mUpperBound) {
// scrollHeight = 8;// 定义向上滚动8个像素,如果可以向上滚动的话
// } else if (y > mLowerBound) {
// scrollHeight = -8;// 定义向下滚动8个像素,,如果可以向上滚动的话
// }
//
// if (scrollHeight != 0) {
// // 真正滚动的方法setSelectionFromTop()
// setSelectionFromTop(dragPosition,
// getChildAt(dragPosition - getFirstVisiblePosition())
// .getTop() + scrollHeight);
// }
}
/**
* 停止拖动,释放资源
*/
private void stopDragging() {
if (mDragView != null) {
WindowManager wm = (WindowManager) getContext().getSystemService(
"window");
wm.removeView(mDragView);
mDragView.setImageDrawable(null);
mDragView = null;
}
if (mDragBitmap != null) {
mDragBitmap.recycle();
mDragBitmap = null;
}
}
public void setDragListener(DragListener l) {
mDragListener = l;
}
public void setDropListener(DropListener l) {
mDropListener = l;
}
public void setRemoveListener(RemoveListener l) {
mRemoveListener = l;
}
public interface DragListener {
void drag(int from, int to);
}
public interface DropListener {
void drop(int from, int to);
}
public interface RemoveListener {
void remove(int which);
}
}