和第一篇大同小异,使用Handler+TimerTask实现计时器功能
activity_main.xml布局文件
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="fatenliyer.f_timertwo.MainActivity" >
<TextView
android:id="@+id/tv_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="40sp" />
</RelativeLayout>
MainActivity.java
package fatenliyer.f_timertwo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public static final int TIMECOUNT = 1;
private TextView tvShow;
private int i = 0;
private int TIME = 1000;
private TimerThread mTimeThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvShow = (TextView) findViewById(R.id.tv_one);
mTimeThread = new TimerThread(tvShow);
timer.schedule(task, TIME, TIME); // 1s后执行task,经过1s再次执行
}
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// 需要做的事:发送消息
Message message = new Message();
message.what = MainActivity.TIMECOUNT;
mTimeThread.sendMessage(message);
}
};
}
TimerHandler.java
package fatenliyer.f_timertwo;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class TimerThread extends Handler{
private TextView mTv;
private int i = 0;
public TimerThread(TextView tv) {
this.mTv = tv;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MainActivity.TIMECOUNT) {
mTv.setText(Integer.toString(i++));
}
}
}
代码下载:
http://download.csdn.net/detail/u014803950/8656227