在 Android 中,拖拽一個圖片(例如 ImageView)到另一個組件(如 LinearLayout、FrameLayout 等容器)涉及以下步驟:
- 準備工作
源組件:你從哪里開始拖動(如 ImageView)。
目標組件:你想把圖片拖到哪里(如 LinearLayout 或其他可接收拖放的容器)。
// 在 onCreate 或 onViewCreated 中設置
ImageView imageView = findViewById(R.id.image_view);
LinearLayout targetLayout = findViewById(R.id.target_container);// 設置長按開始拖拽
imageView.setOnLongClickListener(v -> {ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());ClipData clipData = ClipData.newPlainText("image", "dragged_image");View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(imageView);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {v.startDragAndDrop(clipData, shadowBuilder, imageView, 0);} else {v.startDrag(clipData, shadowBuilder, imageView, 0);}imageView.setVisibility(View.INVISIBLE); // 拖出后隱藏原圖return true;
});// 設置目標區域的監聽
targetLayout.setOnDragListener((v, event) -> {int action = event.getAction();switch (action) {case DragEvent.ACTION_DRAG_ENTERED:// 進入目標區域return true;case DragEvent.ACTION_DROP:// 放開操作View droppedView = (View) event.getLocalState();ViewGroup oldParent = (ViewGroup) droppedView.getParent();if (oldParent != null) {oldParent.removeView(droppedView);}// 添加到新容器((ViewGroup) v).addView(droppedView);droppedView.setVisibility(View.VISIBLE);return true;case DragEvent.ACTION_DRAG_EXITED:// 鼠標離開return true;case DragEvent.ACTION_DRAG_ENDED:// 拖拽結束return true;default:return true;}
});