Android - wait for touch event

2019-07-04 03:04发布

问题:

In my Android app, I'd like to display several images on the screen in sequence, waiting for a touch event (a single tap) to go to the next one. I saw here that one way to do this should be:

public class LoadImage extends Activity {
    private Thread thread; //defined inside the activity

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_load_image);

        [get an image and create a bitmap from it]

        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageBitmap(bitmap);

        thread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this) {
                        wait(100000000); //large number
                    }
                }
                catch(InterruptedException ex) {                    
                }         
            }
        };
        thread.start();    
   }

    @Override
    public boolean onTouchEvent(MotionEvent evt) {
        if (evt.getAction() == MotionEvent.ACTION_DOWN) {
            synchronized (thread) {
                thread.notifyAll();
            }
        }
        return true;
    }
}

However, this code appears to just skip the waiting and immediately jump to the last image. What's wrong with it, and/or is there a better way to do this?

回答1:

By default, event listeners in Android are for waiting - you don't have to provide any delay.

Simply set the onTouchEvent(...) listener on the ImageView and show the first bitmap. When the ImageView is touched, show the next bitmap and so on. All you have to do is keep a count of how many touches there have been in order to know which image to show (image 1, 2, 3, 4 etc).

Example...

public class LoadImage extends Activity {

    int imageNumber = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_image);

        //get an image and create a bitmap from it

        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageBitmap(bitmap);

   }

    @Override
    public boolean onTouchEvent(MotionEvent evt) {
        if (evt.getAction() == MotionEvent.ACTION_DOWN) {
            imageNumber++;
            switch (imageNumber) {
                case 2:
                    // show image 2
                    break;
                case 3:
                    // show image 3
                    break;
                ...
            }
            return true;
        }
        return false;
    }
}