gradeview可拖動效果實現
下麵先上這次實現功能的效果圖:(注:這個效果圖沒有拖拽的時候移動動畫,DEMO裏麵有,可以下載看看)
一、開發心裏曆程
剛開始接觸這個的時候,不知道要如何實現,去網上翻了一大堆資料,懂了個大概,就是目前可以找到的都是拖拽的時候,不帶移動動畫的,和線上的客戶端交互效果相差甚遠,在反反複複的嚐試查看相關東西,大致的做了出來,目前在模擬器上似乎有一點小BUG,真機測試沒有問題,就先放上來,如果發現問題在修改優化。代碼反麵,沒有好好的修改調整,可能會有點亂,請見諒哈。
二、開發前的準備
1.了解重寫View的相關知識,並且知道GridView的一些內部方法,如:怎麼通過觸摸的坐標獲取對應的position等(這裏我采用的是繼承GridView控件)
2.了解屏幕觸摸動作傳遞原理 這裏我以前轉載的一篇或許會有幫助:Android事件分發機製完全解析,帶你從源碼的角度徹底理解(全)
3.了解位移動畫Animation,本DEMO中主要用到:TranslateAnimation 平移動畫
4.了解WindowManager的窗口機製,這裏的item拖拽等都要設計到這個。
5.了解SQLiteDatabase 以及SQLiteOpenHelper等數據庫操作相關的類,本DEMO中主要用到數據庫進行存儲頻道信息,如果你要用文檔進行存儲讀取也可以。
三、開發思路
1. 獲取數據庫中頻道的列表,如果為空,賦予默認列表,並存入數據庫,之後通過對應的適配器賦給對應的GridView
2. 2個GridView--(1.DragGrid 2. OtherGridView)
DragGrid 用於顯示我的頻道,帶有長按拖拽效果
OtherGridView用於顯示更多頻道,不帶推拽效果
注:由於屏幕大小不一定,外層使用ScrollView,所以2者都要重寫計算高度
3. 點擊2個GridView的時候,根據點擊的Item對應的position,獲取position對應的view,進行創建一層移動的動畫層
起始位置:點擊的positiongetLocationInWindow()獲取。終點位置:另一個GridView的最後個ITEM 的position + 1的位置。
並賦予移動動畫,等動畫結束後對2者對應的頻道列表進行數據的remove和add操作。
4. 設置點擊和拖動的限製條件,如 推薦 這個ITEM是不允許用戶操作的。
5. 拖動的DragGrid的操作:
(1)長按獲取長按的ITEM的position -- dragPosition 以及對應的view ,手指觸摸屏幕的時候,調用onInterceptTouchEvent來獲取MotionEvent.ACTION_DOWN事件,獲取對應的數據。由於這裏是繼承了GridView,所以長按時間可以通過setOnItemLongClickListener監聽來執行,或則你也可以通過計算點擊時間來監聽是否長按。
(2)通過onTouchEvent(MotionEvent ev)來監聽手指的移動和抬起動作。當它移動到 其它的item下麵,並且下方的item對應的position 不等於 dragPosition,進行數據交換,並且2者之間的所有item進行移動動畫,動畫結束後,數據更替刷新界麵。
(3) 抬起手後,清除掉拖動時候創建的view,讓GridView中的數據顯示。
6. 退出時候,將改變後的頻道列表存入數據庫。
四、流程圖
下麵是大體的流程圖:
五、核心代碼
- /** GRIDVIEW對應的ITEM點擊監聽接口 */
- @Override
- public void onItemClick(AdapterView<?> parent, final View view, final int position,long id) {
- //如果點擊的時候,之前動畫還沒結束,那麼就讓點擊事件無效
- if(isMove){
- return;
- }
- switch (parent.getId()) {
- case R.id.userGridView:
- //position為 0,1 的不可以進行任何操作
- if (position != 0 && position != 1) {
- final ImageView moveImageView = getView(view);
- if (moveImageView != null) {
- TextView newTextView = (TextView) view.findViewById(R.id.text_item);
- final int[] startLocation = new int[2];
- newTextView.getLocationInWindow(startLocation);
- final ChannelItem channel = ((DragAdapter) parent.getAdapter()).getItem(position);//獲取點擊的頻道內容
- otherAdapter.setVisible(false);
- //添加到最後一個
- otherAdapter.addItem(channel);
- new Handler().postDelayed(new Runnable() {
- public void run() {
- try {
- int[] endLocation = new int[2];
- //獲取終點的坐標
- otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
- MoveAnim(moveImageView, startLocation , endLocation, channel,userGridView);
- userAdapter.setRemove(position);
- } catch (Exception localException) {
- }
- }
- }, 50L);
- }
- }
- break;
- case R.id.otherGridView:
- final ImageView moveImageView = getView(view);
- if (moveImageView != null){
- TextView newTextView = (TextView) view.findViewById(R.id.text_item);
- final int[] startLocation = new int[2];
- newTextView.getLocationInWindow(startLocation);
- final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
- userAdapter.setVisible(false);
- //添加到最後一個
- userAdapter.addItem(channel);
- new Handler().postDelayed(new Runnable() {
- public void run() {
- try {
- int[] endLocation = new int[2];
- //獲取終點的坐標
- userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
- MoveAnim(moveImageView, startLocation , endLocation, channel,otherGridView);
- otherAdapter.setRemove(position);
- } catch (Exception localException) {
- }
- }
- }, 50L);
- }
- break;
- default:
- break;
- }
- }
- <span style="font-size:14px;">private void MoveAnim(View moveView, int[] startLocation,int[] endLocation, final ChannelItem moveChannel,
- final GridView clickGridView) {
- int[] initLocation = new int[2];
- //獲取傳遞過來的VIEW的坐標
- moveView.getLocationInWindow(initLocation);
- //得到要移動的VIEW,並放入對應的容器中
- final ViewGroup moveViewGroup = getMoveViewGroup();
- final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
- //創建移動動畫
- TranslateAnimation moveAnimation = new TranslateAnimation(
- startLocation[0], endLocation[0], startLocation[1],
- endLocation[1]);
- moveAnimation.setDuration(300L);//動畫時間
- //動畫配置
- AnimationSet moveAnimationSet = new AnimationSet(true);
- moveAnimationSet.setFillAfter(false);//動畫效果執行完畢後,View對象不保留在終止的位置
- moveAnimationSet.addAnimation(moveAnimation);
- mMoveView.startAnimation(moveAnimationSet);
- moveAnimationSet.setAnimationListener(new AnimationListener() {
- @Override
- public void onAnimationStart(Animation animation) {
- isMove = true;
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- moveViewGroup.removeView(mMoveView);
- // instanceof 方法判斷2邊實例是不是一樣,判斷點擊的是DragGrid還是OtherGridView
- if (clickGridView instanceof DragGrid) {
- otherAdapter.setVisible(true);
- otherAdapter.notifyDataSetChanged();
- userAdapter.remove();
- }else{
- userAdapter.setVisible(true);
- userAdapter.notifyDataSetChanged();
- otherAdapter.remove();
- }
- isMove = false;
- }
- });
- }</span>
可拖拽的DragGrid代碼:
- public class DragGrid extends GridView {
- /** 點擊時候的X位置 */
- public int downX;
- /** 點擊時候的Y位置 */
- public int downY;
- /** 點擊時候對應整個界麵的X位置 */
- public int windowX;
- /** 點擊時候對應整個界麵的Y位置 */
- public int windowY;
- /** 屏幕上的X */
- private int win_view_x;
- /** 屏幕上的Y */
- private int win_view_y;
- /** 拖動的裏x的距離 */
- int dragOffsetX;
- /** 拖動的裏Y的距離 */
- int dragOffsetY;
- /** 長按時候對應postion */
- public int dragPosition;
- /** Up後對應的ITEM的Position */
- private int dropPosition;
- /** 開始拖動的ITEM的Position */
- private int startPosition;
- /** item高 */
- private int itemHeight;
- /** item寬 */
- private int itemWidth;
- /** 拖動的時候對應ITEM的VIEW */
- private View dragImageView = null;
- /** 長按的時候ITEM的VIEW */
- private ViewGroup dragItemView = null;
- /** WindowManager管理器 */
- private WindowManager windowManager = null;
- /** */
- private WindowManager.LayoutParams windowParams = null;
- /** item總量 */
- private int itemTotalCount;
- /** 一行的ITEM數量 */
- private int nColumns = 4;
- /** 行數 */
- private int nRows;
- /** 剩餘部分 */
- private int Remainder;
- /** 是否在移動 */
- private boolean isMoving = false;
- /** */
- private int holdPosition;
- /** 拖動的時候放大的倍數 */
- private double dragScale = 1.2D;
- /** 震動器 */
- private Vibrator mVibrator;
- /** 每個ITEM之間的水平間距 */
- private int mHorizontalSpacing = 15;
- /** 每個ITEM之間的豎直間距 */
- private int mVerticalSpacing = 15;
- /* 移動時候最後個動畫的ID */
- private String LastAnimationID;
- public DragGrid(Context context) {
- super(context);
- init(context);
- }
- public DragGrid(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- init(context);
- }
- public DragGrid(Context context, AttributeSet attrs) {
- super(context, attrs);
- init(context);
- }
- public void init(Context context) {
- mVibrator = (Vibrator) context
- .getSystemService(Context.VIBRATOR_SERVICE);
- // 將布局文件中設置的間距dip轉為px
- mHorizontalSpacing = DataTools.dip2px(context, mHorizontalSpacing);
- }
- @Override
- public boolean onInterceptTouchEvent(MotionEvent ev) {
- // TODO Auto-generated method stub
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- downX = (int) ev.getX();
- downY = (int) ev.getY();
- windowX = (int) ev.getX();
- windowY = (int) ev.getY();
- setOnItemClickListener(ev);
- }
- return super.onInterceptTouchEvent(ev);
- }
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- // TODO Auto-generated method stub
- boolean bool = true;
- if (dragImageView != null
- && dragPosition != AdapterView.INVALID_POSITION) {
- // 移動時候的對應x,y位置
- bool = super.onTouchEvent(ev);
- int x = (int) ev.getX();
- int y = (int) ev.getY();
- switch (ev.getAction()) {
- case MotionEvent.ACTION_DOWN:
- downX = (int) ev.getX();
- windowX = (int) ev.getX();
- downY = (int) ev.getY();
- windowY = (int) ev.getY();
- break;
- case MotionEvent.ACTION_MOVE:
- onDrag(x, y, (int) ev.getRawX(), (int) ev.getRawY());
- if (!isMoving) {
- OnMove(x, y);
- }
- if (pointToPosition(x, y) != AdapterView.INVALID_POSITION) {
- break;
- }
- break;
- case MotionEvent.ACTION_UP:
- stopDrag();
- onDrop(x, y);
- requestDisallowInterceptTouchEvent(false);
- break;
- default:
- break;
- }
- }
- return super.onTouchEvent(ev);
- }
- /** 在拖動的情況 */
- private void onDrag(int x, int y, int rawx, int rawy) {
- if (dragImageView != null) {
- windowParams.alpha = 0.6f;
- windowParams.x = rawx - win_view_x;
- windowParams.y = rawy - win_view_y;
- windowManager.updateViewLayout(dragImageView, windowParams);
- }
- }
- /** 在鬆手下放的情況 */
- private void onDrop(int x, int y) {
- // 根據拖動到的x,y坐標獲取拖動位置下方的ITEM對應的POSTION
- int tempPostion = pointToPosition(x, y);
- dropPosition = tempPostion;
- DragAdapter mDragAdapter = (DragAdapter) getAdapter();
- // 顯示剛拖動的ITEM
- mDragAdapter.setShowDropItem(true);
- // 刷新適配器,讓對應的ITEM顯示
- mDragAdapter.notifyDataSetChanged();
- }
- /**
- * 長按點擊監聽
- * @param ev
- */
- public void setOnItemClickListener(final MotionEvent ev) {
- setOnItemLongClickListener(new OnItemLongClickListener() {
- @Override
- public boolean onItemLongClick(AdapterView<?> parent, View view,
- int position, long id) {
- int x = (int) ev.getX();// 長安事件的X位置
- int y = (int) ev.getY();// 長安事件的y位置
- startPosition = position;// 第一次點擊的postion
- dragPosition = position;
- if (startPosition <= 1) {
- return false;
- }
- ViewGroup dragViewGroup = (ViewGroup) getChildAt(dragPosition
- - getFirstVisiblePosition());
- TextView dragTextView = (TextView) dragViewGroup
- .findViewById(R.id.text_item);
- dragTextView.setSelected(true);
- dragTextView.setEnabled(false);
- itemHeight = dragViewGroup.getHeight();
- itemWidth = dragViewGroup.getWidth();
- itemTotalCount = DragGrid.this.getCount();
- int row = itemTotalCount / nColumns;// 算出行數
- Remainder = (itemTotalCount % nColumns);// 算出最後一行多餘的數量
- if (Remainder != 0) {
- nRows = row + 1;
- } else {
- nRows = row;
- }
- // 如果特殊的這個不等於拖動的那個,並且不等於-1
- if (dragPosition != AdapterView.INVALID_POSITION) {
- // 釋放的資源使用的繪圖緩存。如果你調用buildDrawingCache()手動沒有調用setDrawingCacheEnabled(真正的),你應該清理緩存使用這種方法。
- win_view_x = windowX - dragViewGroup.getLeft();// VIEW相對自己的X,半斤
- win_view_y = windowY - dragViewGroup.getTop();// VIEW相對自己的y,半斤
- dragOffsetX = (int) (ev.getRawX() - x);// 手指在屏幕的上X位置-手指在控件中的位置就是距離最左邊的距離
- dragOffsetY = (int) (ev.getRawY() - y);// 手指在屏幕的上y位置-手指在控件中的位置就是距離最上邊的距離
- dragItemView = dragViewGroup;
- dragViewGroup.destroyDrawingCache();
- dragViewGroup.setDrawingCacheEnabled(true);
- Bitmap dragBitmap = Bitmap.createBitmap(dragViewGroup
- .getDrawingCache());
- mVibrator.vibrate(50);// 設置震動時間
- startDrag(dragBitmap, (int) ev.getRawX(),
- (int) ev.getRawY());
- hideDropItem();
- dragViewGroup.setVisibility(View.INVISIBLE);
- isMoving = false;
- requestDisallowInterceptTouchEvent(true);
- return true;
- }
- return false;
- }
- });
- }
- public void startDrag(Bitmap dragBitmap, int x, int y) {
- stopDrag();
- windowParams = new WindowManager.LayoutParams();// 獲取WINDOW界麵的
- // Gravity.TOP|Gravity.LEFT;這個必須加
- windowParams.gravity = Gravity.TOP | Gravity.LEFT;
- // 得到preview左上角相對於屏幕的坐標
- windowParams.x = x - win_view_x;
- windowParams.y = y - win_view_y;
- // 設置拖拽item的寬和高
- windowParams.width = (int) (dragScale * dragBitmap.getWidth());// 放大dragScale倍,可以設置拖動後的倍數
- windowParams.height = (int) (dragScale * dragBitmap.getHeight());// 放大dragScale倍,可以設置拖動後的倍數
- this.windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
- | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
- | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
- this.windowParams.format = PixelFormat.TRANSLUCENT;
- this.windowParams.windowAnimations = 0;
- ImageView iv = new ImageView(getContext());
- iv.setImageBitmap(dragBitmap);
- windowManager = (WindowManager) getContext().getSystemService(
- Context.WINDOW_SERVICE);// "window"
- windowManager.addView(iv, windowParams);
- dragImageView = iv;
- }
- /** 停止拖動 ,釋放並初始化 */
- private void stopDrag() {
- if (dragImageView != null) {
- windowManager.removeView(dragImageView);
- dragImageView = null;
- }
- }
- /** 在ScrollView內,所以要進行計算高度 */
- @Override
- public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
- MeasureSpec.AT_MOST);
- super.onMeasure(widthMeasureSpec, expandSpec);
- }
- /** 隱藏 放下 的ITEM */
- private void hideDropItem() {
- ((DragAdapter) getAdapter()).setShowDropItem(false);
- }
- /** 獲取移動動畫 */
- public Animation getMoveAnimation(float toXValue, float toYValue) {
- TranslateAnimation mTranslateAnimation = new TranslateAnimation(
- Animation.RELATIVE_TO_SELF, 0.0F, Animation.RELATIVE_TO_SELF,
- toXValue, Animation.RELATIVE_TO_SELF, 0.0F,
- Animation.RELATIVE_TO_SELF, toYValue);// 當前位置移動到指定位置
- mTranslateAnimation.setFillAfter(true);// 設置一個動畫效果執行完畢後,View對象保留在終止的位置。
- mTranslateAnimation.setDuration(300L);
- return mTranslateAnimation;
- }
- /** 移動的時候觸發 */
- public void OnMove(int x, int y) {
- // 拖動的VIEW下方的POSTION
- int dPosition = pointToPosition(x, y);
- // 判斷下方的POSTION是否是最開始2個不能拖動的
- if (dPosition > 1) {
- if ((dPosition == -1) || (dPosition == dragPosition)) {
- return;
- }
- dropPosition = dPosition;
- if (dragPosition != startPosition) {
- dragPosition = startPosition;
- }
- int movecount;
- // 拖動的=開始拖的,並且 拖動的 不等於放下的
- if ((dragPosition == startPosition)
- || (dragPosition != dropPosition)) {
- // 移需要移動的動ITEM數量
- movecount = dropPosition - dragPosition;
- } else {
- // 移需要移動的動ITEM數量為0
- movecount = 0;
- }
- if (movecount == 0) {
- return;
- }
- int movecount_abs = Math.abs(movecount);
- if (dPosition != dragPosition) {
- // dragGroup設置為不可見
- ViewGroup dragGroup = (ViewGroup) getChildAt(dragPosition);
- dragGroup.setVisibility(View.INVISIBLE);
- float to_x = 1;// 當前下方positon
- float to_y;// 當前下方右邊positon
- // x_vlaue移動的距離百分比(相對於自己長度的百分比)
- float x_vlaue = ((float) mHorizontalSpacing / (float) itemWidth) + 1.0f;
- // y_vlaue移動的距離百分比(相對於自己寬度的百分比)
- float y_vlaue = ((float) mVerticalSpacing / (float) itemHeight) + 1.0f;
- Log.d("x_vlaue", "x_vlaue = " + x_vlaue);
- for (int i = 0; i < movecount_abs; i++) {
- to_x = x_vlaue;
- to_y = y_vlaue;
- // 像左
- if (movecount > 0) {
- // 判斷是不是同一行的
- holdPosition = dragPosition + i + 1;
- if (dragPosition / nColumns == holdPosition / nColumns) {
- to_x = -x_vlaue;
- to_y = 0;
- } else if (holdPosition % 4 == 0) {
- to_x = 3 * x_vlaue;
- to_y = -y_vlaue;
- } else {
- to_x = -x_vlaue;
- to_y = 0;
- }
- } else {
- // 向右,下移到上,右移到左
- holdPosition = dragPosition - i - 1;
- if (dragPosition / nColumns == holdPosition / nColumns) {
- to_x = x_vlaue;
- to_y = 0;
- } else if ((holdPosition + 1) % 4 == 0) {
- to_x = -3 * x_vlaue;
- to_y = y_vlaue;
- } else {
- to_x = x_vlaue;
- to_y = 0;
- }
- }
- ViewGroup moveViewGroup = (ViewGroup) getChildAt(holdPosition);
- Animation moveAnimation = getMoveAnimation(to_x, to_y);
- moveViewGroup.startAnimation(moveAnimation);
- // 如果是最後一個移動的,那麼設置他的最後個動畫ID為LastAnimationID
- if (holdPosition == dropPosition) {
- LastAnimationID = moveAnimation.toString();
- }
- moveAnimation.setAnimationListener(new AnimationListener() {
- @Override
- public void onAnimationStart(Animation animation) {
- // TODO Auto-generated method stub
- isMoving = true;
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- // TODO Auto-generated method stub
- // 如果為最後個動畫結束,那執行下麵的方法
- if (animation.toString().equalsIgnoreCase(
- LastAnimationID)) {
- DragAdapter mDragAdapter = (DragAdapter) getAdapter();
- mDragAdapter.exchange(startPosition,
- dropPosition);
- startPosition = dropPosition;
- dragPosition = dropPosition;
- isMoving = false;
- }
- }
- });
- }
- }
- }
- }
- }
- public class SQLHelper extends SQLiteOpenHelper {
- public static final String DB_NAME = "database.db";// 數據庫名稱
- public static final int VERSION = 1;
- public static final String TABLE_CHANNEL = "channel";//數據表
- public static final String ID = "id";//
- public static final String NAME = "name";
- public static final String ORDERID = "orderId";
- public static final String SELECTED = "selected";
- private Context context;
- public SQLHelper(Context context) {
- super(context, DB_NAME, null, VERSION);
- this.context = context;
- }
- public Context getContext(){
- return context;
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- 最後更新:2017-04-03 12:56:34
上一篇:
ubuntu連接windows遠程桌麵
下一篇:
gradeview可拖動效果實現