如果我想为我的类创建自己的事件监听器,我该如何做?我需要手动维护线程吗?
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.
}
});
以下是完成的方法:
首先创建一个接口类:
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
}
});