다음은 두 개의 단추와 타이머의 예입니다. 타이머가 별도의 엔터티로 실행 중입니다. 하나의 버튼으로 시작하여 다른 버튼으로 멈출 수 있습니다.
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>
출처
2012-03-09 01:39:24
Tim
변수 CDT는 다른 스레드에서 액세스 할 수 있습니다? 나는 최종으로 선언해서는 안된다는 뜻인가요? – Ashwin
나는이 간단한 앱을 포함하기 위해 원래의 답변을 완전히 다시 작성했습니다. 타이머는 한 버튼 클릭으로 시작되고 다른 버튼 클릭으로 취소됩니다. – Tim
답변 해 주셔서 감사합니다. – Ashwin