How to get a continuous Touch Event?

后端 未结 7 1581
死守一世寂寞
死守一世寂寞 2021-01-17 14:01

My class extends View and I need to get continuous touch events on it.

If I use:

public boolean onTouchEvent(MotionEvent me) {

    if(me.getAction()         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 14:28

    I was making a game with a custom view used as a thumb control. . . here is what I did

    float x = 0, y = 0;
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
    
        // handle touch events with 
        switch( event.getActionMasked() ) {
            case MotionEvent.ACTION_DOWN :
                if(cont)
                {
                    // remove any previous callbacks
                    removeCallbacks(contin);
    
                    // post new runnable
                    postDelayed(contin, 10);
                }
                invalidate();
                return true;
            case MotionEvent.ACTION_MOVE :
                if(!cont && thumbing != null)
                {
                    //  do non-continuous operations here
                }
                invalidate();       
                return true;
            case MotionEvent.ACTION_UP :
    
                // set runnable condition to false
                x = 0;
    
                // remove the callbacks to the thread
                removeCallbacks(contin);
                invalidate();
                return true;
            default :
                return super.onTouchEvent(event);
        }
    }
    
    public boolean cont = false;
    
    // sets input to continuous
    public void set_continuous(boolean b) { cont = b; }
    
    
    public Runnable contin = new Runnable()
    {
    
        @Override
        public void run() {
            if(x != 0)
            {
                //  do continuous operations here
                postDelayed(this, 10);
            }
        }
    
    };
    

    A quick note however, make sure in your main activity that is calling this view removes the callbacks manually via the onPause method as follows

    @Override
    protected void onPause() {
        if(left.cont) left.removeCallbacks(left.contin);
        if(right.cont) right.removeCallbacks(left.contin); 
        super.onPause();
    }
    

    That way if you pause and come back touch events aren't being handled twice and the view is free from it's thread's overhead.

    ** tested on Samsung Galaxy S3 with hardware acceleration on **

提交回复
热议问题