Android自定義gridView仿頭條頻道拖動(dòng)管理功能
項(xiàng)目中遇到這樣個(gè)需求:app的功能導(dǎo)航需要可拖動(dòng)排序,類(lèi)似頭條中的頻道拖動(dòng)管理。效果如下,gif不是很順暢,真機(jī)會(huì)好很多。
雖然類(lèi)似的文章網(wǎng)上搜一下有很多,但寫(xiě)的都不令人滿意,注釋不清晰,而且動(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 h1132760021@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)注明出處,謝謝!
上一篇:Android開(kāi)發(fā)簡(jiǎn)易音樂(lè) 器
欄 目:Android
下一篇:android 自定義圓角button效果的實(shí)例代碼(自定義view Demo)
本文標(biāo)題:Android自定義gridView仿頭條頻道拖動(dòng)管理功能
本文地址:http://mengdiqiu.com.cn/a1/Android/8972.html
您可能感興趣的文章
- 01-10Android自定義View之繪制圓形頭像功能
- 01-10Android實(shí)現(xiàn)雙擊返回鍵退出應(yīng)用實(shí)現(xiàn)方法詳解
- 01-10android實(shí)現(xiàn)記住用戶名和密碼以及自動(dòng)登錄
- 01-10android實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能
- 01-10Android 友盟第三方登錄與分享的實(shí)現(xiàn)代碼
- 01-10C++自定義API函數(shù)實(shí)現(xiàn)大數(shù)相乘算法
- 01-10android實(shí)現(xiàn)指紋識(shí)別功能
- 01-10Emoji表情在Android JNI中的兼容性問(wèn)題詳解
- 01-10Android實(shí)現(xiàn)圓形漸變加載進(jìn)度條
- 01-10android開(kāi)發(fā)環(huán)境中SDK文件夾下的所需內(nèi)容詳解


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10Android自定義View之繪制圓形頭像功能
- 01-10Android實(shí)現(xiàn)雙擊返回鍵退出應(yīng)用實(shí)現(xiàn)方
- 01-10android實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能
- 01-10android實(shí)現(xiàn)記住用戶名和密碼以及自動(dòng)
- 01-10C++自定義API函數(shù)實(shí)現(xiàn)大數(shù)相乘算法
- 01-10Android 友盟第三方登錄與分享的實(shí)現(xiàn)代
- 01-10android實(shí)現(xiàn)指紋識(shí)別功能
- 01-10如何給Flutter界面切換實(shí)現(xiàn)點(diǎn)特效
- 01-10Android實(shí)現(xiàn)圓形漸變加載進(jìn)度條
- 01-10Emoji表情在Android JNI中的兼容性問(wèn)題詳
隨機(jī)閱讀
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 04-02jquery與jsp,用jquery