我正在开发一个拖放应用程序,一切正常,但我看到了一个问题。我有 3 个 ImageView,其中两个是可拖动对象,另一个是放置目标。每次我将对象放置在放置目标以外的任何位置时,它都会完全消失!
下面是我使用的代码:
ImageView iv1, iv2, iv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
iv1 = (ImageView) findViewById (R.id.imageView1);
iv2 = (ImageView) findViewById (R.id.imageView2);
iv1.setTag("a");
iv2.setTag("b");
iv3 = (ImageView) findViewById (R.id.imageView3);
iv1.setOnTouchListener(new MyTouchListener());
iv2.setOnTouchListener(new MyTouchListener());
iv3.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 {
//Drawable enterShape = getResources().getDrawable(R.drawable.shape_droptarget);
//Drawable normalShape = getResources().getDrawable(R.drawable.shape);
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_LOCATION:
if(v != iv3)
v.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_STARTED:
// Do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
//handle the dragged view being dropped over a drop view
View view = (View) event.getLocalState();
Drawable dropshadow = getResources().getDrawable(R.drawable.dropshadow);
//view dragged item is being dropped on
ImageView dropTarget = (ImageView) v;
//view being dragged and dropped
ImageView dropped = (ImageView) view;
/*
//if an item has already been dropped here, there will be a tag
Object tag = dropTarget.getTag();
//if there is already an item here, set it back visible in its original place
if(tag!=null)
{
//the tag is the view id already dropped here
int existingID = (Integer)tag;
//set the original view visible again
findViewById(existingID).setVisibility(View.VISIBLE);
}
//set the tag in the target view to the ID of the view being dropped
dropTarget.setTag(dropped.getId());
*/
String temp = "a";
if(temp.equals(view.getTag())){
//dropped.setBackground(dropshadow);
dropTarget.setBackground(dropshadow);
Log.d(temp, "Correct Image");
} else {
Log.d("b", "Wrong Image");
view.setVisibility(View.VISIBLE);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
default:
break;
}
return true;
}
}
我在这里缺少什么?任何帮助都非常感谢。谢谢。