您的位置:首页 > 其它

启动一个倒计时器

2015-12-05 22:33 363 查看
1. 写布局文件,一个输入框输入一个整数,一个文本框显示倒计时,两个按钮分别启动和停止计时

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/et_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10">
<requestFocus />
</EditText>
<TextView
android:id="@+id/tv_showtime"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
s <Button
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始计时" />
<Button
android:id="@+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止计时" />

</LinearLayout>2. 编写MainActivity
public class MainActivity extends Activity implements View.OnClickListener{

private EditText et_time;
private Button btn_start, btn_stop;
private TextView tv_showtime;
private int i = 0;
private Timer timer = null;
private TimerTask task = null;

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

private void initView() {
et_time = (EditText) findViewById(R.id.et_time);
btn_start = (Button) findViewById(R.id.btn_start);
btn_stop = (Button) findViewById(R.id.btn_stop);
tv_showtime = (TextView) findViewById(R.id.tv_showtime);
btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
try {
i = Integer.parseInt(et_time.getText().toString());
tv_showtime.setText(et_time.getText().toString());
startTime();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "输入有误", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_stop:
stopTime();
break;
default:
break;
}
}

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
tv_showtime.setText(msg.arg1 + "");
startTime();
}
};

public void startTime() {
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
i--;
Message message = mHandler.obtainMessage();
message.arg1 = i;
mHandler.sendMessage(message);
}
};
timer.schedule(task, 1000);
}

public void stopTime() {
if(timer != null) {
timer.cancel();
}
}
}使用Timer和Timertask,TimerTask执行一次讲将数字减少1,然后通知handler去改变文本框的内容,然后再次执行倒计时。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: