2014-04-07 36 views
0

我做這樣的事情如何添加一個計時器

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); 

} 

請建議我。

回答

0

嘗試:

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

       @Override 
       public void run() { 

       //Do somthing there 

       } 
      }, 5000); 
+0

這,也取消所有待處理的可運行在處理器與handler.removeCallbacksAndMessages(空),如果前0.5秒的文字修改。否則,所有請求都將被髮送。 – Joris

+0

如果我得到正確的問題,它說DOT 5,這意味着500毫秒。不知道是否錯字 – vilpe89

+0

thx joris。如果文本在0.5秒之前改變,那麼你可以爲「This,並且取消handler.removeCallbacksAndMessages(null)處理程序上的所有待處理runnable。否則所有請求都將被髮送 ' –

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); 
      } 

    } 
} 
相關問題