in my program i 4 imageview, imageview1 and imageview2 should drag and drop to imageview3 and imageview4
imageview1 should drop only in imageview3 and if droped another place should back to original place
and
imageview2 should drop only in imageview4 and if droped another place should back to original place
i write code and i dont know how defined the target of imageview1 and imageview2 and say if drope place exept this target back to original place
package com.test.dragplease;
import android.app.Activity;
import android.content.ClipData;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class DragpleaseActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.imageView1).setOnTouchListener(new MyTouchListener());
findViewById(R.id.imageView2).setOnTouchListener(new MyTouchListener());
findViewById(R.id.imageView3).setOnDragListener(new MyDragListener());
findViewById(R.id.imageView4).setOnDragListener(new MyDragListener());
}
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
class MyDragListener implements OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
//int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
// do nothing
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
//ClipData cd = event.getClipData();
//Item item = cd.getItemAt(0);
//String resp = item.coerceToText(context).toString();
//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;
// dropped.setEnabled(false);
//update the text in the target view to reflect the data being dropped
dropTarget.setBackgroundDrawable(view.getBackground());
dropTarget.setTag(dropped.getId());
break;
case DragEvent.ACTION_DRAG_ENDED:
return false;
default:
break;
}
return true;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…