編輯:進階開發
Android 的拖放(Drag and Drop)框架讓使用者能在同一個布局中,用圖形化的拖曳手勢把資料從一個 View 搬到另一個 View。這個框架由三個部分組成:拖動事件類別、拖動監聽器,以及一組輔助方法與類別。
整個過程可以拆成四個階段:
開始:使用者長按某個項目啟動拖動,應用程式呼叫 startDrag() 通知系統。這個方法的參數包含要拖動的資料、該資料的後設資料,以及一個用來繪製拖曳陰影的回呼。系統會先向應用程式索取拖影並顯示在螢幕上,接著對當前布局中所有已註冊拖動監聽器的 View 送出 ACTION_DRAG_STARTED。
要繼續接收後續的拖動事件(包括可能的放置事件),監聽器必須回傳 true;若回傳 false,它就再也收不到這次操作的任何事件,直到系統送出 ACTION_DRAG_ENDED 為止。
繼續:使用者持續拖動。當拖曳點進入某個 View 的邊界時,該 View 會收到 ACTION_DRAG_ENTERED,其後在邊界內移動時則收到 ACTION_DRAG_LOCATION。監聽器可以在這些時機改變自身外觀或加上高亮,作為視覺回饋。當拖曳點移出邊界,則收到 ACTION_DRAG_EXITED。
放下:使用者在某個 View 的邊界內鬆手,系統對該 View 的監聽器送出 ACTION_DROP。
結束:ACTION_DROP 之後,系統送出 ACTION_DRAG_ENDED 表示整起拖放操作結束。
DragEvent 代表系統在拖放過程各個時間點送出的事件物件,它提供了幾個常數與方法。
| 常數 | 說明 |
|---|---|
| ACTION_DRAG_STARTED | 拖放操作開始 |
| ACTION_DRAG_ENTERED | 拖曳點已進入某 View 的邊界 |
| ACTION_DRAG_LOCATION | 在 ACTION_DRAG_ENTERED 之後,只要拖影仍在該 View 邊界內就會持續送出 |
| ACTION_DRAG_EXITED | 使用者把拖影移出了 View 邊界 |
| ACTION_DROP | 使用者在 View 邊界內放開拖影 |
| ACTION_DRAG_ENDED | 整起拖放操作結束 |
| 方法 | 說明 |
|---|---|
| int getAction() | 取得此事件的動作值 |
| ClipData getClipData() | 回傳呼叫 startDrag() 時傳入的 ClipData 物件 |
| ClipDescription getClipDescription() | 回傳 ClipData 中的 ClipDescription 後設資料 |
| boolean getResult() | 回傳拖放操作的結果指示 |
| float getX() | 取得拖曳點的 X 座標 |
| float getY() | 取得拖曳點的 Y 座標 |
| String toString() | 回傳 DragEvent 物件的字串表示 |
要讓某個 View 對拖動事件有反應,有兩種途徑:實作 View.OnDragListener,或覆寫 onDragEvent(DragEvent) 回呼。兩者被呼叫時都會收到一個 DragEvent 物件。若同時存在,系統會先呼叫監聽器,然後才是回呼方法。
onDragEvent(DragEvent) 搭配 View.OnDragListener 的組合關係,和舊版 Android 中 onTouchEvent() 搭配 View.OnTouchListener 的設計如出一轍。
啟動拖動前,要先建立 ClipData 與其中的 ClipData.Item,並把要搬運的資料放進去;相關後設資料則存在 ClipData 物件內的 ClipDescription 裡。如果這次拖放只是為了搬動畫面上的元件、並不代表資料的移動,那麼也可以傳入 null 而不帶實際物件。
接著建立拖影。你可以繼承 View.DragShadowBuilder 自訂外觀,也可以直接用 View.DragShadowBuilder(View) 產生一個與傳入 View 尺寸相同的預設拖影;此時觸控點會對齊拖影中心。
以下範例用 View.setOnLongClickListener() 啟動拖動,並以 View.OnDragEventListener() 接收事件,拖曳的對象是一張 logo 圖片。
| 步驟 | 說明 |
|---|---|
| 1 | 用 Android Studio 建立專案 DragNDropDemo,目標 SDK 設為最新版本。 |
| 2 | 修改 MainActivity.java,加入事件監聽器與回呼方法。 |
| 3 | 把 logo.png 複製到 res/drawable-* 目錄,可為不同解析度裝置準備不同版本的圖片。 |
| 4 | 修改 res/layout/activity_main.xml,定義 logo 圖片的初始檢視。 |
| 5 | 執行應用程式並驗證結果。 |
MainActivity.java:
package com.yiibai.dragndropdemo; import android.os.Bundle; import android.app.Activity; import android.content.ClipData; import android.content.ClipDescription; import android.util.Log; import android.view.DragEvent; import android.view.View; import android.view.View.DragShadowBuilder; import android.view.View.OnDragListener; import android.widget.*; public class MainActivity extends Activity{ ImageView ima; private static final String IMAGEVIEW_TAG = "Android Logo"; String msg; private android.widget.RelativeLayout.LayoutParams layoutParams; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ima = (ImageView)findViewById(R.id.iv_logo); // Sets the tag ima.setTag(IMAGEVIEW_TAG); ima.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence)v.getTag()); String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN}; ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item); // Instantiates the drag shadow builder. View.DragShadowBuilder myShadow = new DragShadowBuilder(ima); // Starts the drag v.startDrag(dragData, // the data to be dragged myShadow, // the drag shadow builder null, // no need to use local data 0 // flags (not currently used, set to 0) ); return true; } }); // Create and set the drag event listener for the View ima.setOnDragListener( new OnDragListener(){ @Override public boolean onDrag(View v, DragEvent event){ RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams(); switch(event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams(); Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED"); // Do nothing break; case DragEvent.ACTION_DRAG_ENTERED: Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED"); int x_cord = (int) event.getX(); int y_cord = (int) event.getY(); break; case DragEvent.ACTION_DRAG_EXITED : Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED"); x_cord = (int) event.getX(); y_cord = (int) event.getY(); layoutParams.leftMargin = x_cord; layoutParams.topMargin = y_cord; v.setLayoutParams(layoutParams); break; case DragEvent.ACTION_DRAG_LOCATION : Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION"); x_cord = (int) event.getX(); y_cord = (int) event.getY(); break; case DragEvent.ACTION_DRAG_ENDED : Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED"); // Do nothing break; case DragEvent.ACTION_DROP: Log.d(msg, "ACTION_DROP event"); // Do nothing break; default: break; } return true; } }); } }
activity_main.xml 以 RelativeLayout 作為容器,方便我們用邊界距離來定位圖片:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/iv_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/logo" android:contentDescription="@string/drag_drop" /> </RelativeLayout>
strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">DragNDropDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="drag_drop">Click on the image to drag and drop</string> </resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.guidemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.guidemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
執行 DragNDropDemo。請確認 AVD 與環境都已就緒,模擬器視窗如下:
長按畫面上的 Android 標誌大約一秒,拖動手勢就會啟動,圖片開始跟隨你的手指移動。此時你可以把它拖到螢幕上的任何位置並放手:
這個範例刻意在每個 ACTION 分支都寫了 Log,因此你可以在 LogCat 中清楚看到 ACTION_DRAG_STARTED → ENTERED → LOCATION → EXITED → DROP → ENDED 的完整序列。把這些日誌實際跑一遍,比死記常數更能理解拖放流程的節奏。
Android 介面設計入門:布局(Layout)基礎教學
理解布局,是做好 Android 應用設計的關鍵起點。本文提供一份關於布局如何融入 Android 應用架構的概覽,並介紹幾種常用的布局控制元件,說明它們能如何組織應用程
Win7 建置 Android 開發環境(4):裝好 Eclipse
下載 eclipse-java-helios-SR2-win32-x86_64.zip 這個檔案,解壓縮後即可使用;啟動時選擇一個 workspace 目錄就能正常運作。
Android 的兼容性功課:遊戲、儲存空間與影音體驗
Android 手機的開放讓安裝第三方軟體變得容易,這對許多是好事,但也確實埋下了隱患。任何系統都有強項與瑕疵,使用時多留意才是上策。 遊戲:數量有了,質感還不夠 遊戲
Android 與 Linux 的裂痕:授權之爭與開源社群的質疑
Android 包含一個核心庫,提供了 Java 語言核心庫的大部分功能。而論與 Linux 的距離,它比 Mac OS 之於 Linux 還要遠——這樣的形容並不誇張。