2013-06-21 21 views
0

如何重複Toast一段時間,而不是像現在這樣循環考慮定時器延遲?如何重複某些計數的代碼?

public class MainActivity extends Activity { 
    Button btn; 
    EditText edit; 
    TextView view; 
    Timer myTimer = new Timer(); 
    MyTimerTask myTimerTask= new MyTimerTask(); 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btn =(Button)findViewById(R.id.bu); 

     btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) {    
       edit=(EditText)findViewById(R.id.ed1); 
       view=(TextView)findViewById(R.id.te); 

       int aa = Integer.valueOf(edit.getText().toString()); 

       view.setText(edit.getText().toString()); 
       myTimer.scheduleAtFixedRate(myTimerTask, aa, aa); 
      } 
     }); 
    } 

    private class MyTimerTask extends TimerTask { 
     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() 
        //code to do 
        Toast.makeText(getBaseContext(), "Toast test", Toast.LENGTH_SHORT).show(); //how to repeat this toast for certain counts not just looping like now 
      } 
     }); 
    } 
} 

回答

0

您可以在每次執行MyTimerTask.run()時增加一個計數器。然後,當此計數器等於您要顯示Toast通知的次數時,可以用myTimer.cancel();取消TimerTask

+0

我希望Toast顯示的次數將由用戶輸入。所以我需要的是int來將其串起來。請排除我的英語。 – user2509672

+0

在這種情況下,只需將輸入的值存儲在類字段中,並將類字段與計數器進行比較。 – tvkanters

+0

你不覺得如果我使用'CountDownTimer'它會更容易和更簡單嗎?問題仍然是如何重複給我。如果你不介意你能寫一個代碼來重複'CountDownTimer'嗎? – user2509672