效果图
思路分析
新建一个类继承于GridView
public class DragGridView extends GridView
既然是自定义view,那就疯狂得DIY,花样肯定要整起来
既然是推拽,肯定要选择一个国际通用的触发方式——长按啦
既然是长按肯定要有个长按响应的时间
震动器也要加上,增强互交感 变量的注释写再上面
/**
* DragGridView的item长按响应的时间, 默认是1000毫秒,也可以自行设置
*/
private long dragResponseMS = 1000;
/**
* 是否可以拖拽,默认不可以
*/
private boolean isDrag = false;
private int mDownX;
private int mDownY;
private int moveX;
private int moveY;
/**
* 正在拖拽的position
*/
private int mDragPosition;
/**
* 刚开始拖拽的item对应的View
*/
private View mStartDragItemView = null;
/**
* 用于拖拽的镜像,这里直接用一个ImageView
*/
private ImageView mDragImageView;
/**
* 震动器
*/
private Vibrator mVibrator;
private WindowManager mWindowManager;
/**
* item镜像的布局参数
*/
private WindowManager.LayoutParams mWindowLayoutParams;
/**
* 我们拖拽的item对应的Bitmap
*/
private Bitmap mDragBitmap;
/**
* 按下的点到所在item的上边缘的距离
*/
private int mPoint2ItemTop ;
/**
* 按下的点到所在item的左边缘的距离
*/
private int mPoint2ItemLeft;
/**
* DragGridView距离屏幕顶部的偏移量
*/
private int mOffset2Top;
/**
* DragGridView距离屏幕左边的偏移量
*/
private int mOffset2Left;
/**
* 状态栏的高度
*/
private int mStatusHeight;
/**
* DragGridView自动向下滚动的边界值
*/
private int mDownScrollBorder;
/**
* DragGridView自动向上滚动的边界值
*/
private int mUpScrollBorder;
/**
* DragGridView自动滚动的速度
*/
private static final int speed = 80;
/**
* item发生变化回调的接口
*/
private OnChanageListener onChanageListener;
初始化
在DragGridView(Context context, AttributeSet attrs, int defStyle)下
初始化震动器
mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
获取状态栏的高度
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mStatusHeight = getStatusHeight(context);
用来处理是否为长按的Runnable
调用Vibrator.vibrate(int i);可以在里面实现震动效果
private Runnable mLongClickRunnable = new Runnable() {
@Override
public void run() {
isDrag = true; //设置可以拖拽
mVibrator.vibrate(50); //震动一下
mStartDragItemView.setVisibility(View.INVISIBLE);//隐藏该item
//根据我们按下的点显示item镜像
createDragImage(mDragBitmap, mDownX, mDownY);
}
};
拦截触摸事件
这里简单说下MotionEvent
事件 | 简介 |
ACTION_DOWN | 手指 初次接触到屏幕 时触发。 |
ACTION_MOVE | 手指 在屏幕上滑动 时触发,会多次触发。 |
ACTION_UP | 手指 离开屏幕 时触发。 |
ACTION_CANCEL | 事件 被上层拦截 时触发。 |
ACTION_OUTSIDE | 手指 不在控件区域 时触发。 |
移动之前要判断是否点击在GridView的item上面
/**
* 是否点击在GridView的item上面
* @param itemView
* @param x
* @param y
* @return
*/
private boolean isTouchInItem(View dragView, int x, int y){
int leftOffset = dragView.getLeft();
int topOffset = dragView.getTop();
if(x < leftOffset || x > leftOffset + dragView.getWidth()){
return false;
}
if(y < topOffset || y > topOffset + dragView.getHeight()){
return false;
}
return true;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch(ev.getAction()){
case MotionEvent.ACTION_DOWN:
//使用Handler延迟dragResponseMS执行mLongClickRunnable
mHandler.postDelayed(mLongClickRunnable, dragResponseMS);
mDownX = (int) ev.getX();
mDownY = (int) ev.getY();
//根据按下的X,Y坐标获取所点击item的position
mDragPosition = pointToPosition(mDownX, mDownY);
if(mDragPosition == AdapterView.INVALID_POSITION){
return super.dispatchTouchEvent(ev);
}
//根据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() /4;
//获取DragGridView自动向下滚动的偏移量,大于这个值,DragGridView向上滚动
mUpScrollBorder = getHeight() * 3/4;
//开启mDragItemView绘图缓存
mStartDragItemView.setDrawingCacheEnabled(true);
//获取mDragItemView在缓存中的Bitmap对象
mDragBitmap = Bitmap.createBitmap(mStartDragItemView.getDrawingCache());
//这一步很关键,释放绘图缓存,避免出现重复的镜像
mStartDragItemView.destroyDrawingCache();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int)ev.getX();
int moveY = (int) ev.getY();
//如果我们在按下的item上面移动,只要不超过item的边界我们就不移除mRunnable
if(!isTouchInItem(mStartDragItemView, moveX, moveY)){
mHandler.removeCallbacks(mLongClickRunnable);
}
break;
case MotionEvent.ACTION_UP:
mHandler.removeCallbacks(mLongClickRunnable);
mHandler.removeCallbacks(mScrollRunnable);
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(isDrag && mDragImageView != null){
switch(ev.getAction()){
case MotionEvent.ACTION_MOVE:
moveX = (int) ev.getX();
moveY = (int) ev.getY();
//拖动item
onDragItem(moveX, moveY);
break;
case MotionEvent.ACTION_UP:
onStopDrag();
isDrag = false;
break;
}
return true;
}
return super.onTouchEvent(ev);
}
优化视觉体验
拖动过程中要实现拖动的镜像
/**
* 创建拖动的镜像
* @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;
mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left;
mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top - mStatusHeight;
mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE ;
mDragImageView = new ImageView(getContext());
mDragImageView.setImageBitmap(bitmap);
mWindowManager.addView(mDragImageView, mWindowLayoutParams);
}
要想拖动的item实现半透明效果就加上
mWindowLayoutParams.alpha = 0.55f; //透明度
/**
* 从界面上面移动拖动镜像
*/
private void removeDragImage(){
if(mDragImageView != null){
mWindowManager.removeView(mDragImageView);
mDragImageView = null;
}
}
/**
* 拖动item,在里面实现了item镜像的位置更新,item的相互交换以及GridView的自行滚动
* @param x
* @param y
*/
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 Runnable mScrollRunnable = new Runnable() {
@Override
public void run() {
int scrollY;
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);
}
//当我们的手指到达GridView向上或者向下滚动的偏移量的时候,可能我们手指没有移动,但是DragGridView在自动的滚动
//所以我们在这里调用下onSwapItem()方法来交换item
onSwapItem(moveX, moveY);
View view = getChildAt(mDragPosition - getFirstVisiblePosition());
//实现GridView的自动滚动
smoothScrollToPositionFromTop(mDragPosition, view.getTop() + scrollY);
}
};
/**
* 交换item,并且控制item之间的显示与隐藏效果
* @param moveX
* @param moveY
*/
private void onSwapItem(int moveX, int moveY){
//获取我们手指移动到的那个item的position
int tempPosition = pointToPosition(moveX, moveY);
//假如tempPosition 改变了并且tempPosition不等于-1,则进行交换
if(tempPosition != mDragPosition && tempPosition != AdapterView.INVALID_POSITION){
getChildAt(tempPosition - getFirstVisiblePosition()).setVisibility(View.INVISIBLE);//拖动到了新的item,新的item隐藏掉
getChildAt(mDragPosition - getFirstVisiblePosition()).setVisibility(View.VISIBLE);//之前的item显示出来
if(onChanageListener != null){
onChanageListener.onChange(mDragPosition, tempPosition);
}
mDragPosition = tempPosition;
}
}
停止拖拽我们将之前隐藏的item显示出来,并将镜像移除
private void onStopDrag(){
getChildAt(mDragPosition - getFirstVisiblePosition()).setVisibility(View.VISIBLE);
removeDragImage();
}
获取状态栏的高度
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;
}
public interface OnChanageListener{
/**
* 当item交换位置的时候回调的方法,我们只需要在该方法中实现数据的交换即可
* @param form
* 开始的position
* @param to
* 拖拽到的position
*/
public void onChange(int form, int to);
}
设置响应拖拽的毫秒数和回调接口
public void setOnChangeListener(OnChanageListener onChanageListener){
this.onChanageListener = onChanageListener;
}
public void setDragResponseMS(long dragResponseMS) {
this.dragResponseMS = dragResponseMS;
}
加上震动权限
<!--控制振动-->
<uses-permission android:name="android.permission.VIBRATE"/>
使用方法
<{你的包名}.DragGridView
android:id="@+id/dragGridView"
android:listSelector="@android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@android:color/transparent"
android:verticalSpacing="10dip"
android:horizontalSpacing="10dip"
android:stretchMode="columnWidth"
ndroid:gravity="center"
android:numColumns="3" />
位置的标记
private List<HashMap<String, Object>> dataSourceList = new ArrayList<HashMap<String, Object>>();
初始化
DragGridView mDragGridView = (DragGridView) findViewById(R.id.dragGridView);
设置数据
for (int i = 0; i < 30; i++) {
HashMap<String, Object> itemHashMap = new HashMap<String, Object>();
itemHashMap.put("item_image",R.drawable.com_tencent_open_notice_msg_icon_big);
itemHashMap.put("item_text", "拖拽 " + Integer.toString(i));
dataSourceList.add(itemHashMap);
}
拖动监听 Collections处理拖动的数据
final SimpleAdapter mSimpleAdapter = new SimpleAdapter(this, dataSourceList,
R.layout.grid_item, new String[] { "item_image", "item_text" },
new int[] { R.id.item_image, R.id.item_text });
mDragGridView.setAdapter(mSimpleAdapter);
mDragGridView.setOnChangeListener(new OnChanageListener() {
@Override
public void onChange(int from, int to) {
HashMap<String, Object> temp = dataSourceList.get(from);
//直接交互item
// dataSourceList.set(from, dataSourceList.get(to));
// dataSourceList.set(to, temp);
//这里的处理需要注意下
if(from < to){
for(int i=from; i<to; i++){
Collections.swap(dataSourceList, i, i+1);
}
}else if(from > to){
for(int i=from; i>to; i--){
Collections.swap(dataSourceList, i, i-1);
}
}
dataSourceList.set(to, temp);
mSimpleAdapter.notifyDataSetChanged();
}
});