2012-03-20 24 views
0

我正在佈局上顯示佈局底部的結構。我需要在雙擊後顯示,然後在5秒後隱藏它。所以我使用這個倒數計時器:在android的countdowntimer錯誤?

public void timer() 
{ 
    cdt=new CountDownTimer(5000,1000) { 

     @Override 
     public void onTick(long millisUntilFinished) { 

      System.out.println("Timer Working"+millisUntilFinished+""); 

     } 

     @Override 
     public void onFinish() { 

      System.out.println("Finished"); 
      main =(LinearLayout)findViewById(R.id.parent); 

      ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams)main.getLayoutParams(); 
      mlp.height=420; 

      set_up_views(); 
      find_module(); 
      tl.setVisibility(View.INVISIBLE); 


     } 
    }.start(); 

} 

但我不知道如何停止並重新啓動此計時器。我能怎麼做?

回答

1

我建議你不要在這種情況下使用CountDownTimer。

使用Handler.postDelayed(Runnable runnable, long delay)

public class yourActivity extends Activity 
{ 
    public Handler handler = new Handler(); 


    ... 


    public void hideAfter5Sec() 
    { 
     handler.postDelayed(new Runnable() 
     { 
      View view = findViewById(view_to_hide); 
      view.setVisibility(View.INVISIBLE); 
     }, 5000); 

    } 
} 

postDelayed將5秒後執行該代碼。

編輯:

postDelayed將通過Lopper.loop後5秒一次調用()。如果多次調用hideAfter5Sec(),那麼只有你會多次調用postDelayed。

如果你有多個調用hideAfter5Sec()我不認爲有任何錯誤,因爲hideAfter5Sec()只是隱藏它。所以如果它一個或多個你的觀點將被隱藏。

如果你想隱藏只在最後一次調用hideAfter5Sec()時使用這個變體。

public class yourActivity extends Activity 
{ 
    public Handler handler = new Handler(); 
    public long lastHideAfter5Sec = 0L; 

    ... 


    public void hideAfter5Sec() 
    { 
     lastHideAfter5Sec = System.currentTimeMillis(); 
     handler.postDelayed(new Runnable() 
     { 
      if(System.currentTimeMillis() - lastHideAfter5Sec < 5000) 
       return; 
      View view = findViewById(view_to_hide); 
      view.setVisibility(View.INVISIBLE); 
     }, 5000); 

    } 
+0

但是,這也保持運行沒有任何突破!我怎麼能停止並重新啓動? – Navdroid 2012-03-20 14:02:30

+0

請參閱我的編輯說明 – 2012-03-20 14:21:38