Android Custom Event Listener

前端 未结 3 2043
无人共我
无人共我 2020-11-28 02:24

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?

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 03:02

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

提交回复
热议问题