Question

view.setText("hello");
wait(1000);
view.setText("world");

When I call the above function the view doesn't show "hello" at all. The text only updates when the complete function is finished. What do I have to call to see "hello"?

Was it helpful?

Solution

The problem is that you are updating the UI blocking the UI thread and then updating it again. You shouldn't sleep the UI thread, it is bad practice and users will not like it.

Threading would solve the problem, but you really don't need a thread for what you are doing here (also, you shouldn't update the UI from a background thread, you would need to use a handler to send a message).

You should use a handler by itself to do this type of simple update because it doesn't use an additional thread in the application. You can use the postDelayed method on it to have it call back to your UI thread in a specific time.

This article http://developer.android.com/resources/articles/timed-ui-updates.html covers implementing a timed UI update and is pretty straight forward.

To convert your example:

//member variable
private Handler mHandler = new Handler();

//In your current Method
view.setText("hello"); 
mHandler.postDelayed(mUpdateTimeTask, 1000);

//Member variable
private Runnable mUpdateTimeTask = new Runnable() {
   public void run() {
      view.setText("world");      
   }
};

OTHER TIPS

I found this code on developer center and works fine:

view.setText("hello");
new CountDownTimer(1000, 100) {
    TextView view = (TextView) findViewById(R.id.view);

    public void onTick(long millisUntilFinished) { }

    public void onFinish() {         
        view.setText("World!")
    }
}.start();

I think I know what your problem is.

When you modify an UI object, it changes its state but not directly the screen. every system work slightly differently but the basic logic is the same

Main Loop:

1)modifications of the elements 2)refresh screen.

what is happening here is modify to hello wait modify to world refresh.

you making the main thread wait but the interface never refreshes in between time

to solve this you have several ways:

-Thread the modifications so that your wait does not affect the display something like

new Thread(new Runnable(){
    public void run(){
        wait(1000);
        view.setText();
    }
}
  • invalidate the view. it is the way to signal the display that something has change and it needs to redraw.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top