2017-08-29 52 views
0

是否可以創建自定義視圖,這兩個覆蓋功能onTouch()這個自定義視圖裏面執行,並能夠通過​​自定義設置GestureDetector。CustomView壓倒一切onTouch(),並設置附加GestureDetector通過setOnTouchListener()

  1. 我想Override onTouch()方法來實現與觸摸手勢相關的View中的一些繪圖邏輯。
  2. 比我想使用這種自包含的自定義視圖來附加到它的GestureDetector檢測和處理Activity中的這個視圖上的一些自定義手勢。

只有當我有onTouch()繪圖實現,或者只有setOnTouchListener()檢測手勢時,它才適用於我。也許我可以在視圖內放置這個手勢檢測。但我寧願將它作爲單獨鬆散耦合的可重用組件,而不是緊密耦合的手勢檢測器。

回答

1

你可以做somethink這樣的:

public class CustomTouchView extends View { 

    private OnTouchListener onTouchListener; 

    public CustomTouchView(Context context) { 
     super(context); 
    } 

    @Override 
    public void setOnTouchListener(OnTouchListener l) { 
     super.setOnTouchListener(l); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     if (onTouchListener != null) { 
      return onTouchListener.onTouch(this, event); 
     } else { 
      return super.onTouchEvent(event); 
     } 

     // or implement your custom touch logic here 
    } 
} 
+0

這導致我一些解決方案,我認爲。我在CustomTouchView()構造函數setOnTouchListener(this)中使用並實現了onTouch()。所以我改爲製作自定義專用字段TouchViewGestureDetector,並添加setter方法setTouchViewGestureDetector(檢測器)。然後在CustomTouchView中的onTouch覆蓋內,我添加了if(mGestureDetector!= null)mGestureDetector.onTouch(event); –

+0

@MichałZiobro隨時標記我的答案,如果它幫助你。謝謝 –