在Android中我们可以通过对ImageView的ontouch事件进行监听,然后重新layout imageview来拖动它。这种情况下源ImageView也会跟着动。我们如果想实现源ImageView不动而有拖拽效果可以结合OnTouchListener 和 OnDragListener。
、 我们对ImageView设置OnTouchListener 事件,对这个ImageView要拖到的目的区域设置OnDragListener事件。下面贴下代码。
/** * Touch 事件 */ final OnTouchListener movingEventListener = new OnTouchListener() { private int downX; private int downY; public boolean onTouch(View view, MotionEvent motionEvent) { int id = view.getId(); if (Constant.isScanning && (id == R.id.image_picture || id == R.id.image_file || id == R.id.image_music || id == R.id.image_video)) { Toast.makeText(Constant.applicationContext, "正在扫描SDCard,请稍后。", Toast.LENGTH_SHORT).show(); return false; } switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: downX = (int) motionEvent.getX(); downY = (int) motionEvent.getY(); break; case MotionEvent.ACTION_MOVE: int moveX = (int) motionEvent.getX(); int moveY = (int) motionEvent.getY(); int deltaY = moveY - downY; if (Math.abs(deltaY) > 20) { ClipData data = ClipData.newPlainText("", ""); DragShadowBuilder shadowBuilder = new View.DragShadowBuilder( view); view.startDrag(data, shadowBuilder, view, 0); return true; } break; } return false; } };
picture.setOnTouchListener(movingEventListener);
/** * 拖拽事件 * * @Package com.example.privatecloud * @ClassName: DragListener * @date 2013-8-1 上午11:04:48 */ class DragListener 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) { int action = event.getAction(); switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: // Do nothing break; case DragEvent.ACTION_DRAG_ENTERED: v.setBackgroundDrawable(enterShape); break; case DragEvent.ACTION_DRAG_EXITED: v.setBackgroundDrawable(normalShape); break; case DragEvent.ACTION_DROP: // Dropped, reassign View to ViewGroup View view = (View) event.getLocalState(); // ViewGroup owner = (ViewGroup) view.getParent(); // owner.removeView(view); // RelativeLayout container = (RelativeLayout) v; // container.addView(view); startTransmiss(view); view.setVisibility(View.VISIBLE); break; case DragEvent.ACTION_DRAG_ENDED: v.setBackgroundDrawable(normalShape); default: break; } return true; } }
serverLayout.setOnDragListener(new DragListener());
serverLayout就是我们的ImageView要拖拽的目的区域,在ACTION_DROP这个事件时,我们可以执行拖拽成功的操作了。