Android系统。如何中断拖动?

时间:2013-03-05 15:13:54

标签: android drag-and-drop

我正在使用此代码创建拖放:

private final class MyTouchListener implements OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
      if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
        ClipData data = ClipData.newPlainText("", "");

        GlobalTouchX = (int) motionEvent.getX();
        GlobalTouchY = (int) motionEvent.getY();

        shadowBuilder = new MyDragShadowBuilder(view);       

        view.startDrag(data, shadowBuilder, null, 0);

        CurrentDragImage = (ImageView)view;
        view.setVisibility(View.GONE);

        return true;
      } else {
      return false;
      }
    }
  }

如何在不等待丢弃的情况下中断拖放方法,还是可以以编程方式调用drop事件?我尝试了很多方法,但没有运气。例如,如果我可以在这里打断它会很棒:

MainRelative.setOnDragListener(new OnDragListener() {                  
  public boolean onDrag(View v, DragEvent event) {

  int action = event.getAction();

  switch (event.getAction()) {

  case DragEvent.ACTION_DRAG_LOCATION:    

        //!!!!!!!!!!!!!!!
        //HERE I WANT TO INTERRUPT DRAG EVENT ON SOME CONDITION
        //!!!!!!!!!!!!!!!

       break;

  case DragEvent.ACTION_DROP:

       MyOnDrop(v, event, true);                  

       break;
  }

return true;}
});

1 个答案:

答案 0 :(得分:0)

拦截动作的一种方法是覆盖ViewGroup类中的onInterceptTouchEvent(MotionEvent me)方法,如果要拖动到View,则调用此方法。因此,如果需要拦截,则必须放置逻辑在这种方法中。

例如,如果您想使用FrameLayout来保存您的子视图。然后你将不得不创建一个扩展这个FrameLayout类的新类并覆盖onInterceptTouchEvent(MotionEvent me)方法:

class NewFrameLayout extends FrameLayout{


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

     ///Place your logic here to intercept the dragging event


        /*
         * This method JUST determines whether we want to intercept the motion.
         * If we return true, onMotionEvent will be called and we do the actual
         * work here.
         */

        /*
        * Shortcut the most recurring case: the user is in the dragging
        * state and he is moving his finger.  We want to intercept this
        * motion.
        */
    }
}