溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Android自定義gridView仿頭條頻道拖動(dòng)管理功能

發(fā)布時(shí)間:2020-10-21 20:40:58 來(lái)源:腳本之家 閱讀:330 作者:夢(mèng)天2015 欄目:移動(dòng)開(kāi)發(fā)

項(xiàng)目中遇到這樣個(gè)需求:app的功能導(dǎo)航需要可拖動(dòng)排序,類(lèi)似頭條中的頻道拖動(dòng)管理。效果如下,gif不是很順暢,真機(jī)會(huì)好很多。

Android自定義gridView仿頭條頻道拖動(dòng)管理功能

雖然類(lèi)似的文章網(wǎng)上搜一下有很多,但寫(xiě)的都不令人滿(mǎn)意,注釋不清晰,而且動(dòng)畫(huà)還不夠流暢。經(jīng)本人整理優(yōu)化后,拿出來(lái)供后續(xù)有需要的使用。

實(shí)現(xiàn)原理:

  • gridView作為基本控件
  • WindowManager.addView的方式實(shí)現(xiàn)可拖動(dòng)的view
  • TranslateAnimation實(shí)現(xiàn)移動(dòng)動(dòng)畫(huà),動(dòng)畫(huà)完后更新adapter即可

主要的實(shí)現(xiàn)原理上面已經(jīng)說(shuō)明,源碼中關(guān)鍵的地點(diǎn)也有注釋?zhuān)虼讼旅嬷苯由显创a。

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;
/**
 * 長(zhǎng)按拖動(dòng)圖標(biāo)可以調(diào)整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;//拖動(dòng)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();// 算出行數(shù)
    int left = (itemCount % getNumColumns());// 算出最后一行多余的數(shù)量
    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左上角相對(duì)于屏幕的坐標(biāo)
  windowParams.x = rawX - viewL;
  windowParams.y = rawY - viewT;
  //設(shè)置拖拽item的寬和高
  windowParams.width = (int) (dragScale * dragBitmap.getWidth());// 放大dragScale倍,可以設(shè)置拖動(dòng)后的倍數(shù)
  windowParams.height = (int) (dragScale * dragBitmap.getHeight());// 放大dragScale倍,可以設(shè)置拖動(dòng)后的倍數(shù)
  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);//動(dòng)畫(huà)還未執(zhí)行完的情況下,重設(shè)動(dòng)畫(huà)會(huì)清除之前設(shè)置的動(dòng)畫(huà)。
     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) {
    //移動(dòng)位置在還未到新item內(nèi)
    return;
   }
   //移需要移動(dòng)的動(dòng)ITEM數(shù)量
   int moveCount = targetPosition - lastPosition;
   if (moveCount != 0) {
    if (isMoveUp) {//手指抬起時(shí),不執(zhí)行動(dòng)畫(huà)直接交換數(shù)據(jù)
     Adapter adapter = (Adapter) getAdapter();
     adapter.exchange(lastPosition, targetPosition);
     lastPosition = targetPosition;
     isMoving = false;
    } else {
     int moveCountAbs = Math.abs(moveCount);
     float toXvalue = 0, toYvalue = 0;
     //moveXP移動(dòng)的距離百分比(相對(duì)于自己長(zhǎng)度的百分比)
     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) {
        // 如果為最后個(gè)動(dòng)畫(huà)結(jié)束,那執(zhí)行下面的方法
        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);// 設(shè)置一個(gè)動(dòng)畫(huà)效果執(zhí)行完畢后,View對(duì)象保留在終止的位置。
  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實(shí)現(xiàn)起來(lái)就相當(dāng)簡(jiǎn)單了。為了文章完整性,下面也貼上本效果圖的主要使用代碼。

String[] items = new String[]{"頭條", "視頻", "娛樂(lè)", "體育", "北京", "新時(shí)代"
      , "網(wǎng)易號(hào)", "段子", "冰雪運(yùn)動(dòng)", "科技", "汽車(chē)", "輕松一刻"
      , "時(shí)尚", "直播", "圖片", "跟帖", "NBA", "態(tài)度公開(kāi)課"
      , "推薦", "熱點(diǎn)", "社會(huì)", "趣圖", "美女", "軍事"};
      
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,這里需要優(yōu)化,沒(méi)有復(fù)用views。也不能按傳統(tǒng)方式服用view,否則會(huì)造成拖動(dòng)的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;
      }
    });

本文到這就結(jié)束了,有需要的同學(xué)拿到輪子就可以直接使用了,謝謝!

不知道有沒(méi)有眼尖的同學(xué)發(fā)現(xiàn)Adapterd的getView方法中有個(gè) todo需要優(yōu)化。原因是這樣:如果打開(kāi)注釋中的代碼,復(fù)用convertView,會(huì)造成gridView釋放后的新位置一片空白,不知道什么原因,因此折中的方法就是每次都是新生成一個(gè)convertView。

總結(jié)

以上所述是小編給大家介紹的Android自定義gridView仿頭條頻道拖動(dòng)管理功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI