您好,登錄后才能下訂單哦!
項目中遇到這樣個需求:app的功能導航需要可拖動排序,類似頭條中的頻道拖動管理。效果如下,gif不是很順暢,真機會好很多。
雖然類似的文章網上搜一下有很多,但寫的都不令人滿意,注釋不清晰,而且動畫還不夠流暢。經本人整理優化后,拿出來供后續有需要的使用。
實現原理:
主要的實現原理上面已經說明,源碼中關鍵的地點也有注釋,因此下面直接上源碼。
package com.hai.draggrid; import android.content.Context; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; /** * 長按拖動圖標可以調整item位置的Gridview * Created by huanghp on 2019/10/15. * Email h2132760021@sina.com */ public class DragGridView extends GridView { private static final String TAG = "DragGridView"; private int downX, downY; private int rawX, rawY; private int lastPosition = INVALID_POSITION; private int viewL, viewT; private int itemHeight, itemWidth; private int itemCount; private double dragScale = 1.2D;//拖動view的放大比例 private ImageView dragImageView; private WindowManager windowManager = null; private WindowManager.LayoutParams windowParams = null; private boolean isMoving = false; private Animation lastAnimation; private static final long TIME_ANIMATE = 300; public DragGridView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DragGridView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { lastPosition = position; View dragView = getChildAt(lastPosition - getFirstVisiblePosition()); itemHeight = dragView.getHeight(); itemWidth = dragView.getWidth(); itemCount = getCount(); int rows = itemCount / getNumColumns();// 算出行數 int left = (itemCount % getNumColumns());// 算出最后一行多余的數量 if (lastPosition != INVALID_POSITION) { viewL = downX - dragView.getLeft(); viewT = downY - dragView.getTop(); dragView.destroyDrawingCache(); dragView.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(dragView.getDrawingCache()); startDrag(bitmap); dragView.setVisibility(INVISIBLE); isMoving = false; ((Adapter) getAdapter()).setIsDrag(true); requestDisallowInterceptTouchEvent(true); return true; } return false; } }); } private void startDrag(Bitmap dragBitmap) { stopDrag(); windowParams = new WindowManager.LayoutParams(); windowParams.gravity = Gravity.TOP | Gravity.LEFT; //得到preview左上角相對于屏幕的坐標 windowParams.x = rawX - viewL; windowParams.y = rawY - viewT; //設置拖拽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); windowManager.addView(iv, windowParams); dragImageView = iv; } private void stopDrag() { if (dragImageView != null && windowManager != null) { windowManager.removeView(dragImageView); dragImageView = null; } } @Override public boolean onTouchEvent(MotionEvent ev) { int x = (int) ev.getX(); int y = (int) ev.getY(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: downX = x; downY = y; rawX = (int) ev.getRawX(); rawY = (int) ev.getRawY(); break; case MotionEvent.ACTION_MOVE: if (dragImageView != null && lastPosition != INVALID_POSITION) { updateDrag((int) ev.getRawX(), (int) ev.getRawY()); if (!isMoving) onMove(x, y, false); } break; case MotionEvent.ACTION_UP: // Log.e(TAG, "dragImageView is null=" + (dragImageView == null) + ",lastposition=" + lastPosition // + ",pointToPosition=" + pointToPosition(x, y) + ",ismove=" + isMoving); if (dragImageView != null && lastPosition != INVALID_POSITION) { // if (isMoving) onMove(x, y, true);//動畫還未執行完的情況下,重設動畫會清除之前設置的動畫。 stopDrag(); ((Adapter) getAdapter()).setIsDrag(false); ((BaseAdapter) getAdapter()).notifyDataSetChanged(); requestDisallowInterceptTouchEvent(false); } break; } return super.onTouchEvent(ev); } private void onMove(int moveX, int moveY, boolean isMoveUp) { final int targetPosition = pointToPosition(moveX, moveY); if (targetPosition != INVALID_POSITION) { if (targetPosition == lastPosition) { //移動位置在還未到新item內 return; } //移需要移動的動ITEM數量 int moveCount = targetPosition - lastPosition; if (moveCount != 0) { if (isMoveUp) {//手指抬起時,不執行動畫直接交換數據 Adapter adapter = (Adapter) getAdapter(); adapter.exchange(lastPosition, targetPosition); lastPosition = targetPosition; isMoving = false; } else { int moveCountAbs = Math.abs(moveCount); float toXvalue = 0, toYvalue = 0; //moveXP移動的距離百分比(相對于自己長度的百分比) float moveXP = ((float) getHorizontalSpacing() / (float) itemWidth) + 1.0f; float moveYP = ((float) getVerticalSpacing() / (float) itemHeight) + 1.0f; int holdPosition; // Log.d(TAG, "start annimation=" + moveCountAbs); for (int i = 0; i < moveCountAbs; i++) { //從左往右,或是從上往下 if (moveCount > 0) { holdPosition = lastPosition + i + 1; //同一行 if (lastPosition / getNumColumns() == holdPosition / getNumColumns()) { toXvalue = -moveXP; toYvalue = 0; } else if (holdPosition % getNumColumns() == 0) { toXvalue = (getNumColumns() - 1) * moveXP; toYvalue = -moveYP; } else { toXvalue = -moveXP; toYvalue = 0; } } else { //從右往左,或是從下往上 holdPosition = lastPosition - i - 1; if (lastPosition / getNumColumns() == holdPosition / getNumColumns()) { toXvalue = moveXP; toYvalue = 0; } else if ((holdPosition + 1) % getNumColumns() == 0) { toXvalue = -(getNumColumns() - 1) * moveXP; toYvalue = moveYP; } else { toXvalue = moveXP; toYvalue = 0; } } View holdView = getChildAt(holdPosition); Animation moveAnimation = createAnimation(toXvalue, toYvalue); moveAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { isMoving = true; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { // 如果為最后個動畫結束,那執行下面的方法 if (animation == lastAnimation) { Adapter adapter = (Adapter) getAdapter(); adapter.exchange(lastPosition, targetPosition); lastPosition = targetPosition; isMoving = false; } } }); holdView.startAnimation(moveAnimation); if (holdPosition == targetPosition) { lastAnimation = moveAnimation; } } } } } } public Animation createAnimation(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(TIME_ANIMATE); return mTranslateAnimation; } private void updateDrag(int rawX, int rawY) { windowParams.alpha = 0.6f; windowParams.x = rawX - viewL; windowParams.y = rawY - viewT; windowManager.updateViewLayout(dragImageView, windowParams); } static abstract class Adapter extends BaseAdapter { protected boolean isDrag; protected int holdPosition = -1; public void setIsDrag(boolean isDrag) { this.isDrag = isDrag; } public void exchange(int startPosition, int endPositon) { holdPosition = endPositon; } } }
主要的代碼就是DragGridView,拿到此view實現起來就相當簡單了。為了文章完整性,下面也貼上本效果圖的主要使用代碼。
String[] items = new String[]{"頭條", "視頻", "娛樂", "體育", "北京", "新時代" , "網易號", "段子", "冰雪運動", "科技", "汽車", "輕松一刻" , "時尚", "直播", "圖片", "跟帖", "NBA", "態度公開課" , "推薦", "熱點", "社會", "趣圖", "美女", "軍事"}; gridView.setAdapter(new DragGridView.Adapter() { @Override public void exchange(int startPosition, int endPositon) { super.exchange(startPosition, endPositon); String item = list.get(startPosition); if (startPosition < endPositon) { list.add(endPositon + 1, item); list.remove(startPosition); } else { list.add(endPositon, item); list.remove(startPosition + 1); } for (int i = 0; i < list.size(); i++) { Log.e(TAG, "exchange: =" + list.get(i)); } notifyDataSetChanged(); } ...省略部分代碼 @Override public View getView(int position, View convertView, ViewGroup parent) { //todo,這里需要優化,沒有復用views。也不能按傳統方式服用view,否則會造成拖動的view空白 // if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.item, parent, false); // } ((TextView) convertView.findViewById(R.id.tv)).setText(getItem(position)); if (isDrag && position == holdPosition) { convertView.setVisibility(View.INVISIBLE); } else convertView.setVisibility(View.VISIBLE); return convertView; } });
本文到這就結束了,有需要的同學拿到輪子就可以直接使用了,謝謝!
不知道有沒有眼尖的同學發現Adapterd的getView方法中有個 todo需要優化。原因是這樣:如果打開注釋中的代碼,復用convertView,會造成gridView釋放后的新位置一片空白,不知道什么原因,因此折中的方法就是每次都是新生成一個convertView。
希
總結
以上所述是小編給大家介紹的Android自定義gridView仿頭條頻道拖動管理功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。