Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a String letter by letter in a TextView -Android

I have this code:

public void setText(String s){
    TextView tv= (TextView)HomeActivity.tf.getView().findViewById(R.id.textViewFragment);


    char c;
    for(int i=0; i< s.length(); i++){
        c= s.charAt(i);

        tv.append(String.valueOf(c));

        try{
            Thread.sleep(100);
        }catch(Exception e){}
    }
}

The problem is that i cant get the TextView to display the letters one-by-one. After the loop is completed and everything is executed, thats when the text shows up.

I want to have it show up letter by letter, to give an animation effect to the TextView.

like image 707
Plasius Avatar asked Jan 02 '16 19:01

Plasius


2 Answers

This code works,

    public void setText(final String s)
    {
    TextView tv= (TextView)HomeActivity.tf.getView().findViewById(R.id.textViewFragment);
    final int[] i = new int[1];
    i[0] = 0;
    final int length = s.length();
    final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            char c= s.charAt(i[0]);
            Log.d("Strange",""+c);
            tv.append(String.valueOf(c));
            i[0]++;
        }
    };

    final Timer timer = new Timer();
    TimerTask taskEverySplitSecond = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
            if (i[0] == length - 1) {
                timer.cancel();
            }
        }
    };
    timer.schedule(taskEverySplitSecond, 1, 500);
}
like image 150
Parag Kadam Avatar answered Nov 10 '22 11:11

Parag Kadam


Just in case someone's still looking for a better solution (with animating letters), try out Fade-In TextView.

This TextView library inherits its properties directly from the native TextView class, which means that all the native TextView methods are supported. There are practically no limitations including multiline support. It also has some of its own methods and attributes which offer full control over the View.

like image 1
cht Avatar answered Nov 10 '22 12:11

cht