Frage

My app has a not that frequent operation that is executed on the UI threads and takes long time (up to 3 secs). I want to display an animated 'wait' indications during that time. For example, a rotating spinner. No need to display the actual progress, just a fix speed animation.

I created a custom dialog that pops up during the long operation and it has this layout

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinner"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Problem is that it does not spin. How do I make it spin, even if the UI thread is busy?

I tried to create a chain on events to increment it but I get only two events, probably because the UI thread is busy.

// In the custom dialog class. mProgressBar is the ProgressBar in the layout.
// Called externally once when the dialog is shown
public void tick() {
    mProgressBar.incrementProgressBy(10);
    mProgressBar.postDelayed(new Runnable() {
        @Override
        public void run() {
            // Not a recursion since it's done in a future event.
            tick();
        }
    }, 100);
}

What is a simple way to achieve this animation? Will a frame by frame animation be easier to do?

War es hilfreich?

Lösung

Use AsyncTask http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html It is not spin because it is executing in UI thread

Andere Tipps

You may need to set true value to the android:indeterminate property in xml or code

Android: you're doing it wrong...

If you do something that takes a long time on the UI thread, your app freezes. Since you've locked the UI thread, you can't make anything animate (you're lucky to get two ticks), you can't make your app respond to touches or key presses, and your users will see an ANR screen (horrible user experience). Don't ever do any long running task on the UI thread, there is never any good reason to do so.

I'm guessing you want to do the task on the UI thread because what you display depends on the outcome of the task? In that case display a spinner on the main thread, run the task in the background (AsyncTask was designed for exactly this), and then only update you're UI after the task finishes. Same end result without the horrible user experience.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top