Search code examples
androidloopstimedelayprogress

Android: Time delay in a loop with updating UI


What I'm trying to create is a simple progress bar, that would load for ~10 sec. So what I want is a for loop like this:

for(int i = 1; i <= 100; i++) {
                    progressDialog.setProgress(i);
                    //100ms delay
                }

Thanks


Solution

  • The following code may be helpful for you.

    public void startProgress(View view) {
        // Do something long
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    final int value = i;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress(value);
                        }
                    });
                }
            }
        };
        new Thread(runnable).start();
    }