这次就是上一篇的代码补充,以PostDelay实现计时器,采用了递归的算法
布局文件:
<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"
tools:context="fatenliyer.f_timerone.MainActivity" >
<TextView
android:id="@+id/tv_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="40sp" >
</TextView>
</RelativeLayout>
MainActivity
package fatenliyer.f_timerone;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* 计时器, 使用postDelayed实现, 一个递归算法
* 个人不喜欢
*/
public class MainActivity extends ActionBarActivity {
private TextView tvShow;
private int i = 0;
private int TIME = 1000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvShow = (TextView) findViewById(R.id.tv_one);
handler.postDelayed(runnable, TIME); //每隔1s执行 一个典型的递归算法
}
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// handler自带方法实现定时器
try {
handler.postDelayed(runnable, TIME);
tvShow.setText(Integer.toString(i++));
System.out.println("do...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exception...");
}
}
};
}
代码下载:
http://download.csdn.net/detail/u014803950/8656227