Android的自定义事件监听器 [英] Android Custom Event Listener

查看:640
本文介绍了Android的自定义事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想我自己的事件侦听器我的课,我该怎么办呢?我是否需要手工维护一个线程?

解决方案

 公共类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.
    }
 });   

这篇关于Android的自定义事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆