Java how to make a typewriter effect in Java

Java how to make a typewriter effect in Java

To create a typewriter effect in Java, you can use a combination of the Thread.sleep method and the setText method of the TextView class to display the characters of a string one at a time with a delay between each character.

Here is an example of how you can create a typewriter effect in Java using a Runnable:

refer t‮ual:o‬tturi.com
TextView textView = findViewById(R.id.text_view);

final String message = "Hello, World!";
final int delay = 100; // delay in milliseconds

final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        for (int i = 0; i < message.length(); i++) {
            final String character = String.valueOf(message.charAt(i));
            textView.post(new Runnable() {
                @Override
                public void run() {
                    textView.setText(character);
                }
            });
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                // handle exception
            }
        }
    }
};

new Thread(runnable).start();

In this example, a Runnable is defined that iterates over the characters in the message string and sets the text of the textView to the current character using the setText method. The Thread.sleep method is used to add a delay between each character.

You can also use a Handler to create the typewriter effect, as shown in the following example:

TextView textView = findViewById(R.id.text_view);

final String message = "Hello, World!";
final int delay = 100; // delay in milliseconds

final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
    int index = 0;

    @Override
    public void run() {
        if (index < message.length()) {
            final String character = String.valueOf(message.charAt(index));
            textView.setText(character);
            index++;
            handler.postDelayed(this, delay);
        }
    }
};

handler.post(runnable);

In this example, a Handler is used to post the runnable to the message queue and execute it on the main thread. The runnable increments the index variable and sets the text of the textView to the current character using the setText method. The handler.postDelayed method is used to post the runnable to the message queue with a delay between each execution.

Keep in mind that the Thread.sleep and Handler.postDelayed methods should not be used on the main thread, as they can cause the UI to become unresponsive. You should use a separate thread or a Handler to create the typewriter effect to avoid blocking the main thread.

Created Time:2017-11-03 23:27:10  Author:lautturi