Husseinfo
Husseinfo

Reputation: 492

Using Sleep(int ms) in onClick(View arg0)

I am working on this android application: A Button and a textField, the button click change the text of the textField. So i want to add some animation to the button click by changing the text character by character and wait 100 millisecondes before adding each character. But when I run the application and press the button, all the text appear after the sleep time without any animation :p

button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

                    for(int i=0 ; i<str.length() ; i++)
                    {
                        try {

                            Thread.sleep(100);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        txt.append(String.valueOf(str.charAt(i)));
                    }

        }
    });

Upvotes: 0

Views: 157

Answers (2)

Adem
Adem

Reputation: 9429

you block ui thread now and you only see the result of onClick. you should not call sleep in ui thread. this is not best, but it should work

@Override
public void onClick(View arg0) {
    final Handler handler = new Handler();
    new Thread() {
        public void run() {
            for (int i = 0; i < str.length(); i++) {
                final int _i = i;
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
                handler.post(new Runnable() {
                    public void run() {
                        txt.append(String.valueOf(str.charAt(_i)));
                    }
                });
            }
        }
    }.start();
}

Upvotes: 0

ligi
ligi

Reputation: 39519

you do not want to sleep on the main-thread. Better use postDelayed

Upvotes: 3

Related Questions