Search code examples
javaandroidrunnableandroid-handler

Android - wait for runnable to finish


I write text to textview letter by letter. Only after the whole text is displayed I want to start running the progress bar. I guess I can achieve it with notify/wait but I don't know how. Any help?

I created Typewriter class which extends Textview:

private Handler mHandler = new Handler();

public Runnable characterAdder = new Runnable() {
  @Override
  public void run() {
    setText(mText.subSequence(0, mIndex++));
    if (mIndex <= mText.length()) {
      mHandler.postDelayed(characterAdder, mDelay);
    }
  }
};

public void animateText(CharSequence text) {
  mText = text;
  mIndex = 0;
  setText("");
  mHandler.removeCallbacks(characterAdder);
  mHandler.postDelayed(characterAdder, mDelay);
}

and then I use it in Main activity:

Typewriter writer = (Typewriter)findViewById(R.id.typewriter);
writer.animateText("Lorem ipsum dolor sit amet");
//wait until animation finishes to perform further actions

Solution

  • Since both my actions run on UI thread I didn't find any synchronization solution. Instead i postponed the second action by the time needed to print all the letters:

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      public void run() {
        animation.start();
      }
      }, timeNeeded);