如何添加计时器

时间:2014-04-07 12:35:23

标签: android

我正在做这样的事情

Add a timer to the autocompletes for .5 seconds before 
sending a request to the server. If the user types before the 
.5 timer, reset the timer.

我正在尝试onTextChanged()

public void onTextChanged(CharSequence s, int start, int before, int count) {
          /*  String newText = s.toString();
            if(!newText.trim().equals(""))
                Autocompletes_Timer(newText);*/
        }

private Handler handler;
private void Autocompletes_Timer(final String newText) {

    if(handler!= null)
        handler.removeCallbacksAndMessages(null);

    handler = new Handler();
    handler.postDelayed(runnable(newText), 500);

}

请建议我。

2 个答案:

答案 0 :(得分:1)

    public class SomeClass extends Activity implements TextWatcher {

    private Handler serverHandler;

    @Override
    public void onCreate(Bundle savedInstance) {
       serverHandler = new Handler();
       ...

    }

    ...

    public void onTextChanged(CharSequence s, int start, int before, int count) {
       if(!newText.trim().equals(""))
          serverHandler.removeCallbacksAndMessages(null);
          serverHandler.postDelayed(new Runnable() {

                   @Override
                   public void run() {

                   //Do somthing there 

                   }
               }, 500);
          }

    }
}

答案 1 :(得分:0)

试试:

new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                //Do somthing there 

                }
            }, 5000);