I'm trying to make a pretty simple Android app (using Eclipse and Android 4.0.2, API 15) that implements drag & drop. It has an ImageView that needs to be dragged and dropped on a different ImageView. But I seem to be having some sort of problem. The app compiles correctly but I get a force close when I run it on an emulator and on a real device. My code has 3 classes: one for the (only) Activity, one for the "draggable" image listener and one for the "target" image listener:
Activity:
public class MainActivity extends Activity {
ImageView imageToBeDragged = (ImageView)findViewById(R.id.imagetodrag);
ImageView targetImage = (ImageView)findViewById(R.id.target);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageToBeDragged.setOnTouchListener(new ChoiceTouchListener());
targetImage.setOnDragListener(new ChoiceDragListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Draggable listener:
public final class ChoiceTouchListener implements OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
//start dragging the item touched
view.startDrag(data, shadowBuilder, view, 0);
return true;
}
else {
return false;
}
}
}
Target listener:
public class ChoiceDragListener implements OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
//no action necessary
break;
case DragEvent.ACTION_DRAG_ENTERED:
//no action necessary
break;
case DragEvent.ACTION_DRAG_EXITED:
//no action necessary
break;
case DragEvent.ACTION_DROP:
//handle the dragged view being dropped over a target view
View view = (View) event.getLocalState();
//stop displaying the view where it was before it was dragged
view.setVisibility(View.INVISIBLE);
//view dragged item is being dropped on
ImageView dropTarget = (ImageView) v;
//view being dragged and dropped
ImageView dropped = (ImageView) view;
//Dim the target image when the other ImageView is dropped on it
dropTarget.setAlpha(100);
break;
case DragEvent.ACTION_DRAG_ENDED:
//no action necessary
break;
default:
break;
}
return true;
}
}
What can be causing the error?
Thanks!