How to make Android character by character display text animation?


This example demonstrate about How to make Android character by character display text animation.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to src/MainActivity.java

package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Typewriter writer = new Typewriter(this);
      setContentView(writer);
      writer.setCharacterDelay(150);
      writer.animateText("Sample String...Sample String...Sample String...");
   }
}

In the above code, we have taken custom class and added as view to mainActivity. So create a file called Typewriter.java and add the following code -

package com.example.andy.myapplication;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.TextView;

public class Typewriter extends TextView {
   private CharSequence mText;
   private int mIndex;
   private long mDelay = 5000;
   public Typewriter(Context context) {
      super(context);
   }
   public Typewriter(Context context, AttributeSet attrs) {
      super(context, attrs);
   }
   private Handler mHandler = new Handler();
   private 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);
   }
   public void setCharacterDelay(long millis) {
      mDelay = millis;
   }
}

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −


In the above result, it will display text as one character by another character with 5000ms delay.

Click here to download the project code

Updated on: 30-Jul-2019

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements