Lock ontouch listener

2019-09-05 02:10发布

问题:

I want to lock the ontouch listener when the animation is being played. this is my code.

public class MainActivity extends Activity implements OnTouchListener {


 boolean gifIsPlaying;
 long PLAYING_TIME_OF_GIF = 111;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    GIFWebView view = new GIFWebView
            (this, "file:///android_asset/imageedit_ball.gif");


    gifIsPlaying = true;

    new Handler().postDelayed(new Runnable() {
        public void run() {
            gifIsPlaying = false;
        }
    }, PLAYING_TIME_OF_GIF);


    setContentView(view);
    view.setOnTouchListener(this);
    }       

public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    if (gifIsPlaying) {
        // No response to touch events
    } else {
        // Respond to touch events
        GIFWebView view1 = new GIFWebView
                (this, "file:///android_asset/imageedit_ball.gif");

        gifIsPlaying = true;

        new Handler().postDelayed(new Runnable() {
            public void run() {
                gifIsPlaying = false;
            }
        }, PLAYING_TIME_OF_GIF);

        setContentView(view1);
    }

    // Consume touch event
    return true;
}

}

I have tried to implement ontouch within ontouch but no use. I want to temperory lock ontouch till the gif animation completes a loop. Please help.

回答1:

You can try the following if you know the GIF's running time:

Declare a global boolean variable:

boolean gifIsPlaying;
long PLAYING_TIME_OF_GIF = ???;

After creating and adding GIFWebView to your activity's view, set gifIsPlaying to true. Delayed-post a Runnable to set gifIsPlaying to false after PLAYING_TIME_OF_GIF:

gifIsPlaying = true;

new Handler().postDelayed(new Runnable() {
    public void run() {
        gifIsPlaying = false;
    }
}, PLAYING_TIME_OF_GIF);

PLAYING_TIME_OF_GIF will be a long variable.

Inside your onTouch(View, MotionEvent):

public boolean onTouch(View v, MotionEvent event) {
    if (gifIsPlaying) {
        // No response to touch events
    } else {
        // Respond to touch events
        GIFWebView view1 = new GIFWebView
                (this, "file:///android_asset/imageedit_ball.gif");

        gifIsPlaying = true;

        new Handler().postDelayed(new Runnable() {
            public void run() {
                gifIsPlaying = false;
            }
        }, PLAYING_TIME_OF_GIF);

        setContentView(view1);
    }

    // Consume touch event
    return true;
}

If this approach works for you, consider creating a Handler once and reusing it. Same goes for the Runnable.

I don't think there's any other way to solve this problem. There certainly isn't a callback method to inform you that the GIF has run its course.