Skip to content Skip to sidebar Skip to footer

How To Wait After Ui Thread In Android?

In my Activity, I have a method that makes the font size bigger or smaller, depending on the width of a TextView. I do a setText on the TextView to enter a new value (which will mo

Solution 1:

You could delay your code using a Handler:

Handlerh=newHandler();

 h.postDelayed(newRunnable() {

     @Overridepublicvoidrun() {
         // DO DELAYED STUFF
     }
 }, your_variable_amount_of_time); // e.g. 3000 milliseconds

Side note: I do not think that your problem occurs because the setText(...) method takes too much time. Post your code so that others can have a look at it.

Solution 2:

My suggestion would be something like:

        tv.setText("someText");
        new Handler().postDelayed(new Runnable() {

            @Override
            publicvoidrun() {
                int width = tv.getWidth();
                // your code reacting to the change in width
            }
        }, 50);

50 miliseconds should be enough for the change in UI to complete but fast enough for the user not to notice.

As Simon correctly points out this is not necessarily the best solution. To give you an example of how you might use GlobalLayoutListener:

finalViewTreeObservervto= tv.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(newOnGlobalLayoutListener() {
        @OverridepublicvoidonGlobalLayout() {

            width = tv.getWidth();
            // your code reacting to the change in width

        }
    });

Post a Comment for "How To Wait After Ui Thread In Android?"