day01-MinutesToMidnight

来源:互联网 发布:java下载图片怎么过滤 编辑:程序博客网 时间:2024/06/08 10:30

从google上找到的这个项目android-30days-apps,正在看里面的例子。只看了几个就很喜欢了。现在叫30天速成的太多了,但是作者能够坚持去做,坚持了这么多天,也是很有毅力的。在这里感谢一下。

今天练习的例子是时间相关的,界面上显示到午夜还有多长时间,以此记录今天要写的程序还剩多长时间。或者理解成,到今天夜里12点,还有多长时间,再不去完成,够食言了。作者也是从其他两位博主那里借鉴的,要和他们做个马拉松挑战,其中一位是做.NET智能手机的。看看他们的博客,感觉很好玩,有毅力。作者的blog:http://bakhtiyor.com/category/30-days-of-android-apps/。

源代码下载:day01-minutestomidnight

screenshot for MinutestoMidnight

import java.util.Calendar;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;public class MinutesToMidnight extends Activity {private TextView tvCountDown;private TextView tvCurrentTime; // show current timeprivate Timer mTimer;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);/* set font, use ttf file */Typeface font = Typeface.createFromAsset(this.getAssets(),"fonts/digital-7 (mono).ttf");tvCountDown = (TextView) findViewById(R.id.countdown);tvCountDown.setTypeface(font);tvCurrentTime = (TextView)findViewById(R.id.tvCurrentTime);tvCurrentTime.setTypeface(font);//tvCurrentTime.setText(Calendar.getInstance().getTime().toString());/* base only use to change font type, so define as local var. */TextView base = (TextView) findViewById(R.id.base);base.setTypeface(font);}@Overrideprotected void onStart() {super.onStart();mTimer = new Timer("minutes-to-midnight");Calendar calendar = Calendar.getInstance();final Runnable updateTask = new Runnable() {public void run() {tvCountDown.setText(getCountdownString());/* show current time */tvCurrentTime.setText(Calendar.getInstance().getTime().toLocaleString());}};int msec = 999 - calendar.get(Calendar.MILLISECOND);mTimer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {/* Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread. Notes: updateTask will change UI element(tvCountDown).*/runOnUiThread(updateTask);}}, msec, 1000);}@Overrideprotected void onStop() {super.onStop();/* close timer */mTimer.cancel(); // Cancels the Timer and all scheduled tasks.mTimer.purge(); // Removes all canceled tasks from the task queue.mTimer = null;}private String getCountdownString() {Calendar calendar = Calendar.getInstance();int hour = 23 - calendar.get(Calendar.HOUR_OF_DAY);int minute = 59 - calendar.get(Calendar.MINUTE);int second = 59 - calendar.get(Calendar.SECOND);return String.format("%02d:%02d:%02d", hour, minute, second);}} Posted by ian at 04:14  Tagged with: 30days, Android, java
原创粉丝点击