2016-12-24 48 views
0

在我的應用程序中,我有一個倒數計數從五到一。目前,活動開始後,計數器立即開始。我想要的是停留在5秒鐘,等待倒計數,直到觸摸屏幕。所以倒數計時器應該開始觸摸事件。android - 開始一個活動onTouch

public class MainActivity extends Activity implements OnGestureListener { 
    private static final String FORMAT = "%02d:%02d"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game); 

     new CountDownTimer(5000, 10) { 
      public void onTick(long millisUntilFinished) { 
       text.setText("" + String.format("%02d:%03d", 
         TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)), 
         TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)) 
       )); 

       if (animationRunning) { 
        cancel(); 
       } 
      } 

      public void onFinish() { 
       text.setText("done!"); 
      } 
     }.start(); 
    } 


    @Override 
    public boolean onTouchEvent(MotionEvent touchevent) { 

    } 
} 

回答

1

將您的倒計時內onTouch定時器像下面

public class MainActivity extends Activity implements OnGestureListener { 
    private static final String FORMAT = "%02d:%02d"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game); 


    } 


    @Override 
    public boolean onTouchEvent(MotionEvent touchevent) { 
     new CountDownTimer(5000, 10) { 
      public void onTick(long millisUntilFinished) { 
       text.setText("" + String.format("%02d:%03d", 
         TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)), 
         TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)) 
       )); 

       if (animationRunning) { 
        cancel(); 
       } 
      } 

      public void onFinish() { 
       text.setText("done!"); 
      } 
     }.start(); 
    } 
} 
+0

好的,這是有道理的。如果倒計時是方法的一部分,我該怎麼辦? –

+0

在onTouchEvent中調用你的方法,或者爲onTouchEvent創建一個新的倒數計時器:) – Redman

+0

那麼,在應用程序第一次啓動之前,「暫停」活動直到屏幕被觸摸爲止,沒有辦法嗎? –

0

移動的代碼添加到您的onTouchEvent這一部分,因爲它是在活動創建,這就是爲什麼它的開始,當你的活動啓動

new CountDownTimer(5000, 10) { 
    public void onTick(long millisUntilFinished) { 
     text.setText("" + String.format("%02d:%03d", 
       TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)), 
       TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)) 
     )); 

     if (animationRunning) { 
      cancel(); 
     } 
    } 

    public void onFinish() { 
     text.setText("done!"); 
    } 
}.start(); 

你應該沒事