2012-03-09 5 views
0

アンドロイドには、カウントダウンタイマーをキャンセルするcancel()メソッドがあります。しかし、カウントダウンタイマーは別のスレッドで実行されているので、ボタンOnClickLitener()の内部からキャンセルすると、カウントダウンタイマーはキャンセルされます。
buttonOnclickListenerでカウントダウンタイマーが開始されていませんでしたが、onClickListener()内でキャンセルする必要があります。別のスレッドからカウントダウンタイマーを停止する

答えて

2

ここに2つのボタンとタイマーの例を示します。 タイマーは別のエンティティとして実行されています。 1つのボタンで開始し、別のボタンで停止できます。

package com.test; 

import android.app.Activity; 
import android.os.Bundle; 
import android.os.CountDownTimer; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class TimerTestActivity extends Activity { 

    CountDownTimer cdt; 
    TextView display; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button start = (Button) findViewById(R.id.startButton); 
     start.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       setupCountDown(); 
       cdt.start(); 
      } 
     }); 

     Button stop = (Button) findViewById(R.id.stopButton); 
     stop.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       cdt.cancel(); 
      } 
     }); 
     display = (TextView) findViewById(R.id.display); 
    } 

    private void setupCountDown() { 
     cdt = new CountDownTimer(10000, 1000) { 

      public void onTick(long millisUntilFinished) { 
       display.setText("TICK " + millisUntilFinished/1000); 
      } 

      public void onFinish() { 
       display.setText("BUZZZZ"); 
      }   
     }; 
    } 
} 

とmain.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/display" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     /> 

    <Button 
     android:id="@+id/startButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Start" /> 

    <Button 
     android:id="@+id/stopButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Stop" /> 

</LinearLayout> 
+0

は、変数のCDTは、他のスレッドにアクセスできるようになりますか?私は最終的に宣言されるべきではないのですか? – Ashwin

+0

私は、この簡単なアプリを含めるだけで元の答えを完全に書き直しました。タイマーはワンクリックで開始され、別のボタンクリックでキャンセルされます。 – Tim

+0

お返事ありがとうございます。 – Ashwin

関連する問題