2011-11-28 110 views
35

說我想使自己的事件偵聽器,我的課,我該怎麼做呢?我是否需要手動維護線程?Android的自定義事件監聽器

+1

查看代碼路徑的話題[創建自定義監聽器(https://guides.codepath.com/android/Creating-Custom-Listeners) – Suragch

回答

92
public class CustomView extends View(){ 
OnCustomEventListener mListener; 
: 
://some code 
: 
: 

創建將您的活動來實現的接口:

public interface OnCustomEventListener { 
    void onEvent(); 
} 

public void setCustomEventListener(OnCustomEventListener eventListener) { 
    mListener = eventListener; 
} 

現在,你需要知道什麼時候該事件實際發生。例如,當用戶觸摸屏幕上的某個點時,請覆蓋onTouchEvent方法:

onTouchEvent(MotionEvent ev) { 
    if (ev.getAction==MotionEvent.ACTION_DOWN) { 
     if(mListener!=null) 
      mListener.onEvent(); 
    } 
} 

同樣,您可以創建所需的特定事件。 (例子可以觸及,等待2秒鐘並釋放 - 你需要在觸摸事件中做一些邏輯)。

在您的活動,您可以使用customView對象設置一個事件監聽這樣:

customView.setCustomEventListener(new OnCustomEventListener() { 
    public void onEvent() { 
     //do whatever you want to do when the event is performed. 
    } 
}); 
+0

都在OnCustomEventListener接口定義的括號中的錯字? –

+1

糟糕!是的,這是一個錯字,糾正它。謝謝 – rDroid

+0

rDroid,感謝這個例子! OnCustomEventListener接口應該在CustomView類的內部還是外部聲明? – Brabbeldas

5

它可以通過以下方式

首先創建一個接口類來完成:

public interface OnStopTrackEventListener { 
    public void onStopTrack(); 
} 

然後創建一個控制接口的類:

public class Player { 

    private OnStopTrackEventListener mOnStopTrackEventListener; 

    public void setOnStopTrackEventListener(OnStopTrackEventListener eventListener) 
    { 
     mOnStopTrackEventListener = eventListener; 
    } 

    public void stop() 
    { 
     if(mOnStopTrackEventListener != null) 
     { 
      mOnStopTrackEventListener.onStopTrack(); 
     } 

    } 
} 

這是所有。讓我們使用它現在

Player player = new Player(); 
player.stop(); //We are stopping music 
player.setOnStopTrackEventListener(new OnStopTrackEventListener() { 
     @Override 
     public void onStopTrack() { 
      //Code to work when music stops 
     } 
}); 
+0

美麗的代碼。 – Dskato