1 /* 2 * Copyright 2016, The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.dragsource; 18 19 import android.content.ClipData; 20 import android.net.Uri; 21 import android.view.DragEvent; 22 import android.view.View; 23 import android.widget.ImageView; 24 25 /** 26 * OnDragListener for ImageViews. 27 * Sets colors of the target when DragEvents fire. When a drop is received, the {@link Uri} backing 28 * the first {@link android.content.ClipData.Item} in the {@link DragEvent} is set as the image 29 * resource of the ImageView. 30 */ 31 public class ImageDragListener implements View.OnDragListener { 32 33 private static final int COLOR_INACTIVE = 0xFF888888; 34 35 private static final int COLOR_ACTIVE = 0xFFCCCCCC; 36 37 private static final int COLOR_HOVER = 0xFFEEEEEE; 38 39 @Override 40 public boolean onDrag(View view, DragEvent event) { 41 // Change the color of the target for all events. 42 // For the drop action, set the view to the dropped image. 43 switch (event.getAction()) { 44 case DragEvent.ACTION_DRAG_STARTED: 45 setTargetColor(view, COLOR_ACTIVE); 46 return true; 47 48 case DragEvent.ACTION_DRAG_ENTERED: 49 setTargetColor(view, COLOR_HOVER); 50 return true; 51 52 case DragEvent.ACTION_DRAG_LOCATION: 53 processLocation(event.getX(), event.getY()); 54 return true; 55 56 case DragEvent.ACTION_DRAG_EXITED: 57 setTargetColor(view, COLOR_ACTIVE); 58 return true; 59 60 case DragEvent.ACTION_DROP: 61 return processDrop(view, event); 62 63 case DragEvent.ACTION_DRAG_ENDED: 64 setTargetColor(view, COLOR_INACTIVE); 65 return true; 66 67 default: 68 break; 69 } 70 71 return false; 72 } 73 74 private void setTargetColor(View view, int color) { 75 view.setBackgroundColor(color); 76 } 77 78 private boolean processDrop(View view, DragEvent event) { 79 ClipData clipData = event.getClipData(); 80 if (clipData == null || clipData.getItemCount() == 0) { 81 return false; 82 } 83 ClipData.Item item = clipData.getItemAt(0); 84 if (item == null) { 85 return false; 86 } 87 Uri uri = item.getUri(); 88 if (uri == null) { 89 return false; 90 } 91 return setImageUri(view, event, uri); 92 } 93 94 protected void processLocation(float x, float y) { 95 } 96 97 protected boolean setImageUri(View view, DragEvent event, Uri uri) { 98 if (!(view instanceof ImageView)) { 99 return false; 100 } 101 ((ImageView) view).setImageURI(uri); 102 return true; 103 } 104 } 105