1. 程式人生 > >Android實現簡單倒計時

Android實現簡單倒計時

package com.example.jishiq;


import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity implements OnClickListener {
private Button start = null;
private Button zstart = null;
private Button end = null;
private Button dedao = null;
private EditText edit = null;
private TextView tv = null;
private Timer time = null;
private TimerTask task = null;
private TimerTask task1 = null;
private int i = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) this.findViewById(R.id.end);
end = (Button) this.findViewById(R.id.start);
edit = (EditText) this.findViewById(R.id.Edit);
tv = (TextView) this.findViewById(R.id.textView);
zstart = (Button) this.findViewById(R.id.zstart);
dedao = (Button) this.findViewById(R.id.dedao);
dedao.setOnClickListener(this);
start.setOnClickListener(this);
end.setOnClickListener(this);
zstart.setOnClickListener(this);
}


@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.dedao:
tv.setText(edit.getText().toString());
i = Integer.parseInt(edit.getText().toString());
// 建立時間物件
break;
case R.id.start:
// 獲取時間
starttime();
break;
case R.id.zstart:
// 獲取時間
time.cancel();
tv.setText("0");
break;
case R.id.end:
stoptime();
break;
}
}


Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
tv.setText(msg.arg1 + "");
// tv.setText(msg.arg2+"");
starttime();
}
};


private void starttime() {
time = new Timer();
task = new TimerTask() {
@Override
public void run() {
i--;
Message msg = handler.obtainMessage();
msg.arg1 = i;
handler.sendMessage(msg);
}
};
time.schedule(task, 1000);


}


private void stoptime() {
time.cancel();


}


}