说我想我自己的事件侦听器我的课,我该怎么办呢?我是否需要手工维护一个线程?
解决方案 公共类CustomView扩展视图(){
OnCustomEventListener mListener;
:
://一些code
:
:
创建将你的活动来实现的接口:
公共接口OnCustomEventListener {
无效的onEvent();
}
公共无效setCustomEventListener(OnCustomEventListener事件监听){
mListener =事件监听;
}
现在,你需要知道什么时候该事件实际发生。例如,当用户触摸屏幕上的一个点,覆盖的onTouchEvent方法:
的onTouchEvent(MotionEvent EV){
如果(ev.getAction == MotionEvent.ACTION_DOWN){
如果(mListener!= NULL)
mListener.onEvent();
}
}
同样,您可以创建你想要一个特定的事件。 (例子可能是触摸了下来,等待了整整2秒钟,获释后,你需要做的触摸事件里面的一些逻辑)。
在你的活动,你可以使用customView对象来设置的EventListener这样:
customView.setCustomEventListener(新OnCustomEventListener(){
公共无效的onEvent(){
//做你想做的时候进行的情况下做的。
}
});
Say I want to make my own event listener for my class, how do I do that? Do I need to maintain a thread manually?
解决方案public class CustomView extends View(){
OnCustomEventListener mListener;
:
://some code
:
:
Create an interface that will be implemented by your activity:
public interface OnCustomEventListener {
void onEvent();
}
public void setCustomEventListener(OnCustomEventListener eventListener) {
mListener = eventListener;
}
Now you need to know when the event is actually occurring. For example when the user touches a point on screen, override onTouchEvent method:
onTouchEvent(MotionEvent ev) {
if (ev.getAction==MotionEvent.ACTION_DOWN) {
if(mListener!=null)
mListener.onEvent();
}
}
Similarly, you can create a specific event that you want. (examples could be touch down, wait for exactly 2 seconds and release- you would need to do some logic inside touch event).
In your activity, you can use the customView object to set an eventListener as such:
customView.setCustomEventListener(new OnCustomEventListener() {
public void onEvent() {
//do whatever you want to do when the event is performed.
}
});