2013-03-05 53 views
2

我使用這個代碼來創建拖放:Android。如何中斷拖動?

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; 
     } 
    } 
    } 

我怎樣才能打斷拖動的方法,而無需等待下降,或者我可以掉話事件編程?我嘗試了很多方法,但沒有運氣。例如,這將是巨大的,如果我可以在這裏打斷它:

攔截動作將覆蓋onInterceptTouchEvent(MotionEvent我)在一個ViewGroup類方法的
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;} 
}); 

回答

0

的一種方法,這種方法被稱爲如果您拖動在視圖上,所以如果你需要攔截你將不得不將邏輯放在這個方法中。

例如,如果你想使用FrameLayout來保存你的子視圖。然後,你必須創建擴展這個的FrameLayout類的新類,並覆蓋onInterceptTouchEvent(MotionEvent我)方法:

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. 
     */ 
    } 
} 
+0

謝謝你的答案。十分感謝!我已經在xml文件中設計了它的父元素 - RelativeLayout。因此,如果使用您提供的方式,我需要以編程方式創建此Parent RelativeLayout,並使用onInterceptTouchEvent。所以我需要以編程方式創建所有視圖,更正?沒有辦法使用xml文件進行設計?也許有辦法覆蓋現有的RelativeLayout onInterceptTouchEvent? – 2013-03-05 22:43:27

+0

你可以做的是創建自定義的RelativeLayout,然後在xml中使用它。例如,如果RelativeLayoutNew是新類,那麼它將簡單地替換xml文件中的RelativeLayout。我希望這是有道理的。 – 2013-03-06 09:04:57