`

在LiistView内拖放Item

阅读更多
package com.mylist;

import com.mylist.ListViewInterceptor.DropListener;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
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;

public class ListViewInterceptor extends ListView {

	private DropListener mDropListener;

	private ImageView mDragView;
	private int mDragPos; // which item is being dragged
	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

	private Rect mTempRect = new Rect();
	private final int mTouchSlop;
	private int mHeight;
	private int mUpperBound;
	private int mLowerBound;
	private WindowManager mWindowManager;
	private WindowManager.LayoutParams mWindowParams;
	private int dragndropBackgroundColor = 0x00000000;
	private Bitmap mDragBitmap;
	private int mItemHeightHalf = 32;
	private int mItemHeightNormal = 64;
	private int mItemHeightExpanded = 128;

	public ListViewInterceptor(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public ListViewInterceptor(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		Log.v(">>>>>>>>>>onTouchEvent", ">>>>>>>>>>onTouchEvent");
		if ((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) {

						mDragPos = itemnum;
						doExpansion();
						Log.v(">>>doExpansion", ">>>>>>>>>>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(0, mHeight / 2);
//						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());
//						if (v != null) {
//							int pos = v.getTop();
//							setSelectionFromTop(ref, pos - speed);
//
//						}
//					}
				}
				break;
			}
			return true;
		}
		return super.onTouchEvent(ev);

	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		if (mDropListener != null) {
			switch (ev.getAction()) {
			case MotionEvent.ACTION_DOWN:
				int x = (int) ev.getX();
				int y = (int) ev.getY();
				int itemnum = pointToPosition(x, y);
				Log.v("itemnum>>>", ">>>>>>>>" + itemnum);
				if (itemnum == AdapterView.INVALID_POSITION) {
					break;
				}
				ViewGroup item = (ViewGroup) getChildAt(itemnum
						- getFirstVisiblePosition());
				Log.v("itemnum>>>", ">>>>>>>>" + getFirstVisiblePosition()
						+ "---" + ev.getRawY() + "----" + ev.getY()+"-----"+item.getTop());
				mDragPoint = y - item.getTop();
				mCoordOffset = ((int) ev.getRawY()) - y;
				View dragger = item.findViewById(R.id.img);
				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());
					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);
	}

	private void startDragging(Bitmap bm, int y) {
		stopDragging();

		mWindowParams = new WindowManager.LayoutParams();
		mWindowParams.gravity = Gravity.TOP;
		mWindowParams.x = 0;
		mWindowParams.y = y - mDragPoint + mCoordOffset;

		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);
		v.setImageBitmap(bm);
		mDragBitmap = bm;

		mWindowManager = (WindowManager) getContext()
				.getSystemService("window");
		mWindowManager.addView(v, mWindowParams);
		mDragView = v;
	}

	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;
		}
	}

	private void dragView(int x, int y) {
		float alpha = 1.0f;
		mWindowParams.alpha = alpha;
		// }
		mWindowParams.y = y - mDragPoint + mCoordOffset;
		mWindowManager.updateViewLayout(mDragView, mWindowParams);
	}

	private int getItemForPosition(int y) {
		int adjustedy = y - mDragPoint - mItemHeightHalf;
		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);
		}
	}

	/*
	 * 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(x, y)) {
				return getFirstVisiblePosition() + i;
			}
		}
		return INVALID_POSITION;
	}

	public interface DropListener {
		void drop(int from, int to);
	}

	public void setDropListener(DropListener onDrop) {
		// TODO Auto-generated method stub
		mDropListener = onDrop;
	}

}

 

package com.mylist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ListActivity {
	/** Called when the activity is first created. */

	private MyAdapter adapter = null;
	private ArrayList<Map<String, Object>> array;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		array = getData();
		adapter = new MyAdapter();
		setListAdapter(adapter);
		ListViewInterceptor tlv = (ListViewInterceptor) getListView();

		tlv.setDropListener(onDrop);

		tlv.getAdapter();
	}

	private ListViewInterceptor.DropListener onDrop = new ListViewInterceptor.DropListener() {
		@Override
		public void drop(int from, int to) {
			Map item = adapter.getItem(from);

			adapter.remove(item);
			adapter.insert(item, to);

		}
	};

	class MyAdapter extends ArrayAdapter<Map<String, Object>> {

		MyAdapter() {
			super(MainActivity.this, R.layout.mylist, array);
		}

		public ArrayList<Map<String, Object>> getList() {
			return array;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.mylist, parent, false);
			}
			TextView label = (TextView) row.findViewById(R.id.title);
			label.setText(array.get(position).get("title").toString());
			TextView info = (TextView) row.findViewById(R.id.info);
			info.setText(array.get(position).get("info").toString());
			ImageView imageView = (ImageView) row.findViewById(R.id.img);
			imageView.setImageResource(Integer.valueOf(array.get(position)
					.get("img").toString()));
			return (row);
		}
	}

	private ArrayList<Map<String, Object>> getData() {
		ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "闆峰摜鑰佽寖");
		map.put("info", "绠€浠? 鑰佽寖鍚嶅彨鑼冩槬闆凤紝鐢熶簬鍏崄骞翠唬銆?);
		map.put("img", R.drawable.fan);

		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "闆惫");
		map.put("info", "绠€浠? 銆€浠庢椂闂翠笂璐┛浜嗘暣涓姉鏃ユ垬浜夋椂鏈熴€?);
		map.put("img", R.drawable.xue);

		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "澹叺绐佸嚮");
		map.put("info", "绠€浠? 榫熷効瀛愮殑璁镐笁澶氭墠浼氭湁浜涘嚭鎭€?);
		map.put("img", R.drawable.shi);

		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", "閾佽楠戝叺");
		map.put("info", "绠€浠? 浠?949骞?鏈堜笂娴锋垬褰圭殑鍏抽敭涔嬫垬娴︿笢");
		map.put("img", R.drawable.tie);

		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "鐖卞嚭鑹?);
		map.put("info", "绠€浠?璁茶堪涓庢椂灏氭湁鍏崇殑閮藉競鐖辨儏杞诲枩鍓с€?);
		map.put("img", R.drawable.ai);

		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "鑳岀潃浣犺烦鑸?);
		map.put("info", "绠€浠?澶╂墠鑸炶箞婕斿憳澶忕拠");
		map.put("img", R.drawable.bei);
		list.add(map);
		return list;
	}
}

 

分享到:
评论

相关推荐

    两个Recyclerview之间利用View.onDragListener相互拖放item交换数据(Drag-on-Drop)

    两个Recyclerview之间利用View.onDragListener相互拖放item交换数据(Drag-on-Drop),并且可以拖放排序,同一个Recyclerview之间利用ItemTouchHelper进行拖放排序.

    Visual C++源代码 8 如何在控件中实现拖放功能

    Visual C++源代码 8 如何在控件中实现拖放功能Visual C++源代码 8 如何在控件中实现拖放功能Visual C++源代码 8 如何在控件中实现拖放功能Visual C++源代码 8 如何在控件中实现拖放功能Visual C++源代码 8 如何在...

    ListView item 动态拖放改变位置

    1. **监听触摸事件**:我们需要在ListView的item视图上添加OnTouchListener,以便捕获用户的滑动和拖放操作。通常,我们可以重写MotionEvent的ACTION_DOWN、ACTION_MOVE和ACTION_UP事件来判断是否开始拖放、拖动过程...

    ListView內部拖放

    在某些应用场景下,可能需要实现`ListView`控件中项的拖放功能,例如调整列表项的位置或重新组织数据等。本文将详细介绍如何在C#中实现`ListView`内部单个与多个项的拖放操作。 #### 二、基础知识 ##### 1. Drag ...

    listview拖放

    在.NET Framework或WPF等平台上,ListView提供了丰富的功能,其中包括拖放操作。本文将深入探讨如何实现ListView的拖放功能,允许用户将一个ListView中的项目拖动到另一个ListView。 一、拖放基本原理 拖放操作...

    易语言DragDrop拖放源码

    "DragDrop拖放源码"是指使用易语言编写的,能够实现窗口元素(如文件、图标等)通过鼠标拖动并在指定区域内释放来完成特定操作的代码。这种技术广泛应用于文件管理器、桌面应用以及各种自定义界面的设计中,使得用户...

    delphi 窗体接受拖放

    在Delphi编程环境中,拖放(Drag and Drop)功能是一种常用的操作方式,允许用户通过鼠标将数据从一个位置移动到另一个位置。在本场景中,我们关注的是如何使Delphi的窗体(Form)能够接收并处理拖放事件。这个功能...

    火山PC文件拖放.zip

    3. **跨应用程序拖放**:普通拖放功能可能受限于同一应用程序内的文件操作,而火山PC文件拖放可能支持跨应用程序的拖放,比如从资源管理器拖文件到邮件客户端,或者从下载管理器拖文件到文档编辑器。 4. **文件类型...

    易语言源码拖放文件取路径(拖放组件应用).zip

    在易语言中,我们可以通过使用特定的组件来实现各种功能,其中包括拖放组件。这个“易语言源码拖放文件取路径(拖放组件应用).zip”文件是一个示例项目,它演示了如何利用易语言的拖放功能来获取用户拖入的文件路径...

    vb 鼠标对listbox的项进行拖拽 拖放,item位置移动

    在一些应用场景中,我们可能希望用户能够通过鼠标拖放操作来改变Listbox中项的顺序,以实现更直观和交互式的数据管理。本篇文章将详细解释如何在VB中实现Listbox项的拖拽功能,使item位置可以移动。 首先,我们需要...

    C#控件数据拖放操作

    在C#编程中,数据拖放(Drag and Drop)功能是一项常用的技术,它允许用户通过鼠标将数据从一个位置拖放到另一个位置。在本主题中,我们将深入探讨如何实现C#控件之间的数据拖放操作,以及如何在控件内部进行此类...

    解决易语言WIN10不能拖放对象方法及例子(纯源码)

    在易语言编程中,有时会遇到在Windows 10操作系统上无法进行对象拖放的问题。这个问题通常是由于系统兼容性或编程接口使用不当导致的。本文将深入探讨如何解决易语言在WIN10环境下对象拖放功能失效的问题,并提供一...

    如何在PowerBuild8.0中实现拖放技术

    在PowerBuilder 8.0中实现拖放技术是一项常见的用户界面增强功能,它允许用户通过鼠标将一个对象从一处拖动到另一处,以完成数据的移动或操作的执行。这种技术大大提升了软件的易用性和用户体验。以下将详细介绍如何...

    VB文件拖放操作实例

    在VB(Visual Basic)编程环境中,文件拖放操作是一种常见的用户界面交互功能,它允许用户通过鼠标将文件从桌面或其他位置直接拖放到应用程序窗口中,从而实现文件的导入或执行某些基于文件的操作。这个"VB文件拖放...

    易语言实现文件拖放功能模块源码

    文件拖放是Windows操作系统中的一个常见功能,用户可以通过鼠标将文件从一个位置直接拖到另一个位置,这种交互方式在很多应用中得到了广泛的应用,如文件管理器、编辑器、邮件客户端等。 易语言的文件拖放功能主要...

    listview拖放排序

    在`DragDrop`事件中,通过`e.Data.GetDataPresent("System.Windows.Forms.ListViewItem")`检查拖放的数据是否是ListViewItem。如果是,可以获取`ListViewItem`对象,然后使用`ListView.Items.IndexOf()`和`ListView...

    API多文件拖放.rar

    在这个“API多文件拖放.rar”压缩包中,我们可以预见到包含的资源是关于如何在易语言环境下实现多文件拖放功能的源代码。易语言是一种面向对象的、易于学习和使用的编程语言,特别适合初学者和快速开发应用。 拖放...

    支持拖放功能的FlatListforReactNative

    然而,标准的`FlatList`并不直接支持拖放(drag-and-drop)功能,但在实际应用场景中,比如创建待办事项列表、调整照片顺序等,这种功能非常有用。针对这一需求,开发者们创建了`react-native-draggable-flatlist`库...

    html5图片拖放

    4. 控制拖放行为:在`dragenter`和`dragover`事件中,阻止默认行为并设置允许拖放的样式。 5. 执行拖放操作:在`drop`事件中,获取`dataTransfer`中的数据,然后根据需求处理,如创建新的图片元素并插入到DOM中。 ...

    CTreeCtrl中节点的拖放

    5. **拖放过程**:在`CTreeCtrl`的`OnMouseDown`或`OnMouseMove`事件中,检测是否满足启动拖放的条件(例如,按下鼠标左键并移动一定距离),然后调用`DoDragDrop`函数启动拖放操作。 6. **处理`Drop`事件**:在`...

Global site tag (gtag.js) - Google Analytics