2016-02-23 30 views
0

在子對象中,我們需要跟蹤座標(ACTION_MOVE)。如果座標爲getX() > x,我們必須將事件發送給父對象。Android:處理觸摸事件在父子發送(OnTouchListener)

問題:要將事件發送給父級,我們需要返回false,但是如果返回false,我們將無法跟蹤子級中對象的座標。

public boolean onTouch(View v,MotionEvent e) { 
    if (e.getAction() == MotionEvent.ACTION_MOVE) { 
     if (e.getY() > 200) { 
      return false; //we must send event to the parent object, but since then the ACTION_MOVE event no longer occurs here 
     } else { 
      myView.setTranslationY(e.getY()); 
      return true; //we have to handle the event here 
     } 
    } 
    return false; 
} 

如何正確處理這兩種情況?

回答

0

您可以在子類中定義一個接口,並由父接口實現。當您需要將事件發送到父對象,可以調用接口的方法,這樣的事情:

子類:

 public boolean onTouch(View v,MotionEvent e){ 
    if(e.getAction()==MotionEvent.ACTION_MOVE){ 
     if(e.getY()>200){ 
      super.onTouchChildListener(v,e); 
     }else{ 
      myView.setTranslationY(e.getY()); 
     } 
      return true; 
    } 
    return false; 
} 

... 

public interface OnChildListener { 
    void onTouchChildListener(View v, MotionEvent e); 
}