我好像没有完全理解Android的拖放功能。
我已经设置了4个不同的视图,并将它们的onDragListener
设置为以下代码。我希望用户能够将图片拖放到这四个视图之一。当用户释放被拖动的图片时,我希望在其所在的视图上填充相关数据。
问题在于,在ACTION_DRAG_ENDED
时,所有四个视图都会响应,返回event.getResult() = true
。只有一个视图在拖拽视图进入包围区域时响应。根据Android文档(此处),除非发送了ACTION_DROP,否则event.getResult()
返回false。但是所有四个视图都显示true,只有一个视图显示ACTION_DROP(请参见下面的Logcat)。
Java代码
private OnDragListener mydragListener = new OnDragListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
ClipData dragData;
boolean handled = false;
switch (action) {
case DragEvent.ACTION_DRAG_STARTED: {
dragSku = event.getClipDescription().getLabel().toString();
handled = true;
Log.d(TAG,"ACTION_DRAG_STARTED="+handled);
} break;
case DragEvent.ACTION_DRAG_ENDED: {
// Report the drop/no-drop result to the user
final boolean dropped = event.getResult();
if (dropped) {
Log.d(TAG,"THIS SHOULD BE DROPPED: "+v.toString());
handled = true;
}
else {
handled = false;
}
Log.d(TAG,"ACTION_DRAG_ENDED="+handled);
} break;
case DragEvent.ACTION_DROP:
// Gets the item containing the dragged data
ClipData.Item item = event.getClipData().getItemAt(0);
// Returns true. DragEvent.getResult() will return true.
handled = true;
Log.d(TAG,"ACTION_DROP="+handled);
break;
case DragEvent.ACTION_DRAG_EXITED: {
handled = false;
Log.d(TAG,"ACTION_DRAG_EXITED="+handled);
} break;
case DragEvent.ACTION_DRAG_ENTERED: {
handled = true;
Log.d(TAG,"ACTION_DRAG_ENTERED="+handled);
}
}
return handled;
}
};
日志记录:
12-10 12:13:56.240: D/BrowsePhonesDevices(25667): ClipData : ClipData { text/plain "sku340603" {T:sku} } : sku340603
12-10 12:13:56.275: D/BrowsePhonesDevices(25667): ACTION_DRAG_STARTED=true
12-10 12:13:56.275: D/BrowsePhonesDevices(25667): ACTION_DRAG_STARTED=true
12-10 12:13:56.275: D/BrowsePhonesDevices(25667): ACTION_DRAG_STARTED=true
12-10 12:13:56.275: D/BrowsePhonesDevices(25667): ACTION_DRAG_STARTED=true
12-10 12:13:56.960: D/BrowsePhonesDevices(25667): ACTION_DRAG_ENTERED=true
12-10 12:13:57.205: D/BrowsePhonesDevices(25667): ACTION_DROP=true
12-10 12:13:57.205: I/ViewRootImpl(25667): Reporting drop result: true
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): THIS SHOULD BE DROPPED: android.widget.ImageView@42dfa5f0
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): ACTION_DRAG_ENDED=true
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): THIS SHOULD BE DROPPED: android.widget.ImageView@42dee7b0
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): ACTION_DRAG_ENDED=true
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): THIS SHOULD BE DROPPED: android.widget.ImageView@42df7618
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): ACTION_DRAG_ENDED=true
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): THIS SHOULD BE DROPPED: android.widget.ImageView@42df8e48
12-10 12:13:57.215: D/BrowsePhonesDevices(25667): ACTION_DRAG_ENDED=true
myDragListener
需要做出哪些改变,才能使只有一个视图从event.getResult()
中获得true的结果?