user1834464
user1834464

Reputation:

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 most likely increase or decrease the width of the ViewText) and then go right into my method. My problem is that when I enter my method, the size of the TextView has not changed yet, so I'm guessing the UI thread is taking a bit more time to accomplish the resize of the TextView and my method does not work because of that. So how do I wait after the UI thread so that I can correctly execute the code of my method?

This is the code of my main activity. The method texteAffichage is just setting what is in my TextView and gestionPolice is resizing the font if it needs to. When I do a sysout in gestionPolice, I never get the current width of the TextView, because it seems like it did not have time to do that.

affichage.setText(texteAffichage((Button) v));
gestionPolice();

Upvotes: 1

Views: 1779

Answers (2)

cYrixmorten
cYrixmorten

Reputation: 7108

My suggestion would be something like:

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

            @Override
            public void run() {
                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:

    final ViewTreeObserver vto = tv.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

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

        }
    });

Upvotes: 1

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

You could delay your code using a Handler:

 Handler h = new Handler();

 h.postDelayed(new Runnable() {

     @Override
     public void run() {
         // 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.

Upvotes: 2

Related Questions