简体   繁体   中英

Android: Handling touch events for OpenGL-ES

While implementing touch events I noticed that I couldn't update a variable in MotionEvent.ACTION_DOWN case to be "received" in the MotionEvent.ACTION_UP case. The variable just seemed to go out of scope. (Code below)

 public boolean onTouchEvent(MotionEvent e) {

    float x = e.getX();
    float y = e.getY();
    boolean Finger_Down = false;
    float   PowerBar    = 0;
    float   CurrentPowerLevel   = 0;

    switch (e.getAction()) {

        case MotionEvent.ACTION_DOWN:
            PowerBar=1;
            break;

        case MotionEvent.ACTION_UP:
            mRenderer.mPlayer.Tx-=PowerBar;             
            break;     
    }
    return true;
}

The purpose of the code is to simply raise the power level in the MotionEvent.ACTION_DOWN case, and have it execute the intensity in the MotionEvent.ACTION_UP case.

I can perform the behaviors individually, ie:

case MotionEvent.ACTION_DOWN:
mRenderer.mPlayer.Tx-=0.01f;                
break;

or:

case MotionEvent.ACTION_UP:
mRenderer.mPlayer.Tx-=0.01f;                
break;

But not otherwise as intuitively expected. Is there another event methodology that I should be doing/overlooking?

EDIT:

This behavior continues for touch listener:(below)

this.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            float Foo=0;
            if(event.getAction()==MotionEvent.ACTION_DOWN){
                Foo=0.1f;
                return true;
            }
            if(event.getAction()==MotionEvent.ACTION_UP){
                mRenderer.mPlayer.Tx=Foo;
                return true;
            }
            if(event.getAction()==MotionEvent.ACTION_MOVE){
                return true;
            }

            return false;
        }
    });

Use: return true; rather than break; and substitute return false where you return true;

It was a scope issue, Foo was originally being declared and initialized as float Foo = 0; within the onTouch() implementation. When the event was consumed, the function would return and no more events accessed. Upon the next iteration, onTouch() is again called, and Foo initialized to 0 .

...

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            float Foo=0;
            if(event.getAction()==MotionEvent.ACTION_DOWN){
                Foo-=0.1f;
                return true;
            }

Declaring Foo outside of the onTouch() function resolved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM