編輯:關於 Android 程式設計
GridView 是 Android 開發中相當常見的元件,功能強大,但實戰裡總會遇到框架沒有直接支援的需求。網路上關於「拖動 GridView 中 item 位置」的範例已經很多,這裡不再重複;本文要談的是另一個更細顆度的玩法——拖動 item 裡面的內容。
先看一眼效果:








為了方便示範,每個 item 用數字作為內容,並以不同背景色區分。長按任一 item 後即可拖動:拖離的那一格數字 −1,拖到的那一格數字 +1。理解原理之後,把它改造成「真正可移動 item 位置」的 GridView 並不難——事實上,那些讓人百思不得其解的花式桌面亂序排列,用同樣的思路也能做出來。
整個方案可以拆成四步:
1. 截圖:在 ACTION_DOWN 時開啟 drawingCache,把被觸摸的 item 轉成一張 Bitmap。
2. 延遲判定長按:用 postDelayed 延遲 1 秒設置長按標記,避免與普通點擊衝突。
3. 浮動層:長按成立後,把截圖包成 ImageView,透過 WindowManager 加到手機視窗最上層,跟著手指移動;同時在接近上下邊緣時觸發列表自動滾動。
4. 落地:手指抬起時,計算目標位置、驗證是否落在有效區域內,再更新資料並 notifyDataSetChanged()。
package com.freedom.gridview;
import android.annotation.SuppressLint;
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.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import com.freedom.gridview.adapter.GridViewAdapter;
import com.freedom.gridview.bean.Data;
/**
* 可移動 item 內容的 GridView
*/
@SuppressLint("NewApi")
public class FreedomGridView extends GridView {
// 是否在移動中
private boolean isMove = false;
// 是否是第一次移動
private boolean isFirst = true;
// 是否已觸發長按
private boolean isLongClick = false;
// 被拖動 item 的截圖
private Bitmap bitmap;
// 浮動的移動視圖
private ImageView moveView = null;
// 手指與浮動視圖之間的偏移量
private int offsetX, offsetY;
// 觸摸位置(起始)
private int touchPositionInScreen;
// 移動的目標位置
private int moveToPosition;
// 觸摸點在 item 內部的座標
private int touchPositionInItemX, touchPositionInItemY;
// 系統判定的最小觸發距離
private int scaledTouchSlop;
// 觸及上下邊距時的自動滾動距離
private int upScrollBounce;
private int downScrollBounce;
// 視窗管理者,用於懸浮移動視圖
private WindowManager windowManager = null;
private WindowManager.LayoutParams layoutParams = null;
private GridViewAdapter adapter;
public FreedomGridView(Context context) {
super(context);
scaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public FreedomGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FreedomGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* 長按判定:一秒後才認為是長按
*/
private Runnable longPressRun = new Runnable() {
@Override
public void run() {
isLongClick = true;
}
};
/**
* 判斷觸摸座標是否落在視圖內部
*/
private boolean contains(View v, int xInView, int yInView) {
if (v instanceof ImageView) {
return ((ImageView) v).getDrawable().getBounds().contains(xInView, yInView);
}
return v.getBackground().getBounds().contains(xInView, yInView);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (null == adapter || adapter.isEmpty()) {
adapter = (GridViewAdapter) getAdapter();
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
int x = (int) ev.getX();
int y = (int) ev.getY();
// 定位被觸摸的 item
touchPositionInScreen = moveToPosition = this.pointToPosition(x, y);
if (moveToPosition == AdapterView.INVALID_POSITION) {
break;
}
ViewGroup itemView = (ViewGroup) this.getChildAt(
moveToPosition - this.getFirstVisiblePosition());
// 觸摸點相對於 item 的偏移
touchPositionInItemY = y - itemView.getTop();
touchPositionInItemX = x - itemView.getLeft();
// 判斷是否落在 item 內部的目標視圖上
View view = itemView.findViewById(R.id.desk_back);
if (this.contains(view, touchPositionInItemX, touchPositionInItemY)) {
try {
int[] locationInScreen = new int[2];
view.getLocationOnScreen(locationInScreen);
} catch (NullPointerException e) {
break;
}
}
// 浮動視圖相對於手指的偏移
this.offsetX = (int) (ev.getRawX() - x);
this.offsetY = (int) (ev.getRawY() - y);
// 計算觸發自動滾動的邊距
upScrollBounce = Math.min(y - scaledTouchSlop, getHeight() / 3);
downScrollBounce = Math.max(y + scaledTouchSlop, getHeight() * 2 / 3);
// 開啟截圖快取
itemView.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(itemView.getDrawingCache());
itemView.destroyDrawingCache();
postDelayed(longPressRun, 1000);
break;
}
case MotionEvent.ACTION_MOVE: {
if (isLongClick) {
int mx = (int) ev.getX();
int my = (int) ev.getY();
// 第一次移動時才建立浮動視圖
if (isFirst) initWindowManager(bitmap, mx, my);
onMove(mx, my);
removeCallbacks(longPressRun);
return true;
}
break;
}
case MotionEvent.ACTION_UP: {
int upX = (int) ev.getX();
int upY = (int) ev.getY();
if (isMove && isLongClick) {
stopMove();
completeMove(upX, upY);
isMove = false;
isLongClick = false;
break;
}
removeCallbacks(longPressRun);
break;
}
}
return super.onTouchEvent(ev);
}
/**
* 建立浮動的移動視圖
*/
public void initWindowManager(Bitmap bm, int x, int y) {
stopMove();
isFirst = false;
layoutParams = new WindowManager.LayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.horizontalMargin = 0;
layoutParams.verticalMargin = 0;
layoutParams.x = x - touchPositionInItemX + offsetX;
layoutParams.y = y - touchPositionInItemY + offsetY;
layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
layoutParams.format = PixelFormat.TRANSLUCENT;
layoutParams.windowAnimations = 0;
windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
ImageView moveViewTemp = new ImageView(getContext());
moveViewTemp.setImageBitmap(bm);
windowManager.addView(moveViewTemp, layoutParams);
moveView = moveViewTemp;
}
/**
* 移除浮動視圖
*/
public void stopMove() {
if (moveView != null) {
windowManager.removeView(moveView);
moveView = null;
}
}
/**
* 移動過程中的回調
*/
public void onMove(int x, int y) {
isMove = true;
int tempPosition = this.pointToPosition(x, y);
if (tempPosition != FreedomGridView.INVALID_POSITION) {
this.moveToPosition = tempPosition;
}
if (moveView != null) {
layoutParams.alpha = 0.8f;
layoutParams.y = y - touchPositionInItemY + offsetY;
layoutParams.x = x - touchPositionInItemX + offsetX;
windowManager.updateViewLayout(moveView, layoutParams);
}
// 靠近上下邊緣時自動滾動
int scrollHeight = 0;
if (y < upScrollBounce) {
scrollHeight = 30;
} else if (y > downScrollBounce) {
scrollHeight = -30;
}
if (scrollHeight != 0) {
smoothScrollToPositionFromTop(moveToPosition,
getChildAt(moveToPosition - getFirstVisiblePosition()).getTop() + scrollHeight, 1);
}
}
/**
* 移動結束,落地並更新資料
*/
public void completeMove(int x, int y) {
isFirst = true;
int tempPosition = this.pointToPosition(x, y);
if (tempPosition != FreedomGridView.INVALID_POSITION) {
this.moveToPosition = tempPosition;
}
// 拖到列表之外,不做處理
if (y < getChildAt(0).getTop()) {
return;
} else if (y > getChildAt(getChildCount() - 1).getBottom()) {
moveToPosition = getAdapter().getCount() - 1;
return;
}
if (moveToPosition >= 0 && moveToPosition < getAdapter().getCount()) {
ViewGroup itemView = (ViewGroup) this.getChildAt(
moveToPosition - this.getFirstVisiblePosition());
if (itemView != null) {
ImageView imageView = (ImageView) itemView.findViewById(R.id.desk_back);
boolean isIn = this.contains(imageView,
x - itemView.getLeft(), y - itemView.getTop());
if (isIn && moveToPosition != touchPositionInScreen) {
itemView.startAnimation(
AnimationUtils.loadAnimation(getContext(), R.anim.desk_scale));
Data touchData = (Data) adapter.getItem(touchPositionInScreen);
if (touchData.getNum() == 0) {
Toast.makeText(getContext(), "數目為 0 不可變化", Toast.LENGTH_SHORT).show();
return;
}
Data toData = (Data) adapter.getItem(moveToPosition);
if (toData.getNum() == 2) {
Toast.makeText(getContext(), "數目為 2 不可變化", Toast.LENGTH_SHORT).show();
return;
}
touchData.setNum(touchData.getNum() - 1);
toData.setNum(toData.getNum() + 1);
adapter.notifyDataSetChanged();
}
}
}
}
}
截圖時機:一定要在 ACTION_DOWN 就開啟 drawingCache,等到長按成立再截圖,item 可能已經被高亮或改寫。
浮動層要關掉觸摸:FLAG_NOT_TOUCHABLE 加上 FLAG_NOT_FOCUSABLE,浮動的 ImageView 才不會把 ACTION_UP 事件吃掉,否則手勢會中斷。
自動滾動的邊距:這裡取的是「觸摸 Y 減去 touchSlop」與「螢幕高度三分之一」的較小值,實測手感比較自然,可依實際 item 高度微調。
資料邊界:示例用數字 −1 / +1 演示,真實場景通常要換成列表的 swap 或 remove/insert,並記得在非法操作時給出提示並阻止 notifyDataSetChanged()。
完整專案可到 www.2cto.com 下載。理解以上原理後,把 completeMove() 中的「數字增減」替換為「資料搬移」,就是一個可拖拽排序的 GridView 了。
Activity 入門實踐:從第一個按鈕到選單的完整流程
照著《第一行代碼 Android》的脈絡走一遍 Activity 的基本用法,過程有點像當年敲 Java 的 Hello World——步驟簡單,但幾個容易踩的小坑值得記
小米手環接入微信教學:步數與排行榜隨時看
小米手環接入微信,可查看步數與排行榜。開啟小米手環App,點右上角更多,進入服務,選擇微信接入。 按下微信接入後會跳轉微信,關注小米手環官方帳號,即可進入公眾號查看運動資
Android 顏色資源使用完全指南
前言在 Android 開發中,顏色資源可分為兩種:一種是自行定義的顏色,另一種是使用系統內建的顏色。自訂顏色Android 的顏色值由透明度 alpha 與 RGB(紅
Android 自定義 EditText:打造內建清除按鈕與抖動提示
問題背景 Android 原生輸入框預設沒有 iOS 常見的一鍵清除功能。若只在版面中排列 EditText 與圖片,雖然直觀,卻會增加層級,也可能遇到文字過長覆蓋圖片的