Android - wait for touch event

女生的网名这么多〃 提交于 2019-12-12 14:21:24

问题


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


来源:https://stackoverflow.com/questions/12360810/android-wait-for-touch-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!