Android中的倒计时

2024-08-31 20:38
文章标签 android 倒计时

本文主要是介绍Android中的倒计时,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、在Android中使用到的计时/倒计时方式

1,统一布局文件            activity_main.xml文件

<span style="font-size:18px;"><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=".MainActivity">//用于显示计时效果<TextViewandroid:id="@+id/show"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world"android:textSize="20sp" />
</RelativeLayout></span>
2,具体实现方式

(一)Timer、TimerTask   【倒计时模式】

<span style="font-size:18px;">public class MainActivity extends Activity {private TextView tv;private int timeDownStart = 88;Timer timer = new Timer();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);//延迟2秒   执行周期:每隔1秒执行一次timer.schedule(task, 2000, 1000);}/*** 第一种倒计时方式:Timer 和 TimerTask*/TimerTask task = new TimerTask() {@Overridepublic void run() {runOnUiThread(new Runnable() {@Overridepublic void run() {timeDownStart--;tv.setText(timeDownStart + "");if (timeDownStart < 0) {timer.cancel();tv.setText("tv finish----------");}}});}};
}</span>
(二)Timer、TimerTask、Handler   【倒计时模式】
<span style="font-size:18px;">public class MainActivity extends Activity {private TextView tv;private int timeDownStart = 66;Timer timer = new Timer();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);timer.schedule(task, 0, 1000);//不延迟}/*** 第二种倒计时方式*/TimerTask task = new TimerTask() {@Overridepublic void run() {timeDownStart--;Message msg = new Message();msg.what = 1;handler.sendMessage(msg);}};Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:tv.setText(timeDownStart + "");if (timeDownStart < 0) {timer.cancel();tv.setText("tv finish!");}break;}super.handleMessage(msg);}};}</span>
(三)Handler 和Message   【倒计时模式】
<span style="font-size:18px;">public class MainActivity extends Activity {private TextView tv;private int timeDownStart = 66;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);Message msg = handler.obtainMessage(1);handler.sendMessageDelayed(msg, 1000);}/*** 第三种倒计时方式*/Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:timeDownStart--;tv.setText(timeDownStart + "");if (timeDownStart > 0) {Message msg = handler.obtainMessage(1);handler.sendMessageDelayed(msg, 1000);} else {tv.setText("tv finish~_~");}break;}super.handleMessage(msg);}};
}</span>

(四)Handler 和 Thread 【计时模式】

<span style="font-size:18px;">public class MainActivity extends Activity {/*** 第四种计时方式:Handler 和 Thread*/private TextView tv;private int startNum = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);new Thread(new MyThread()).start();//没有停止}/*** 第四种计时方式*/class MyThread implements Runnable {@Overridepublic void run() {while (true) {try {Thread.sleep(1000);Message msg = new Message();msg.what = 1;handler.sendMessage(msg);} catch (InterruptedException e) {e.printStackTrace();}}}}Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:startNum++;tv.setText(startNum + "");break;}super.handleMessage(msg);}};
}</span>
(五)Handler 和 Runnable【计时模式】
<span style="font-size:18px;">public class MainActivity extends Activity {/*** 第五种计时方式:Handler 和 Runnable*/private TextView tv;private int startNum = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);handler.postDelayed(runnable, 1000);}/*** 第五种计时方式*/Handler handler = new Handler();Runnable runnable = new Runnable() {@Overridepublic void run() {startNum++;tv.setText(startNum + "");handler.postDelayed(runnable, 1000);}};
}</span>
(六)CountDownTimer【倒计时模式】
<span style="font-size:18px;">public class MainActivity extends Activity {/*** 第六种倒计时方式:CountDownTimer*/private MyCount mc;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.show);mc = new MyCount(30000, 1000);mc.start();}/*** 第六种倒计时方式:CountDownTimer*/class MyCount extends CountDownTimer {public MyCount(long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);}@Overridepublic void onTick(long millisUntilFinished) {tv.setText("请等待30秒(" + millisUntilFinished / 1000 + ")...");Toast.makeText(MainActivity.this, "bababba", Toast.LENGTH_SHORT);//toast有延迟显示}@Overridepublic void onFinish() {tv.setText("tv finish。。。。。。");}}
}</span>
       第五种方式最简洁,第六种方式最实用;Handler会实时刷新界面,同时也就最耗资源;开启子线程启动刷新比较合理,但是在销毁的时候一定先销毁子线程,释放资源。

二、时间选择器

1,时间选择xml布局文件   date_picker_layout

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><DatePickerandroid:id="@+id/datePicker"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal" /><EditTextandroid:id="@+id/dateEt"android:layout_width="fill_parent"android:layout_height="wrap_content"android:cursorVisible="false"android:editable="false" /><TimePickerandroid:id="@+id/timePicker"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal" /><EditTextandroid:id="@+id/timeEt"android:layout_width="fill_parent"android:layout_height="wrap_content"android:cursorVisible="false"android:editable="false" /></LinearLayout></span>

2,实现主类

<span style="font-size:18px;">public class DatePickerActivity extends Activity {private EditText dateEt = null;private EditText timeEt = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.date_picker_layout);dateEt = (EditText) findViewById(R.id.dateEt);timeEt = (EditText) findViewById(R.id.timeEt);DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);/****************************************************************************/datePicker.updateDate(2014,10,10);timePicker.setCurrentHour(16);/****************************************************************************/Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
//        int monthOfYear = calendar.get(Calendar.MONTH);
//        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);//year, monthOfYear, dayOfMonth,datePicker.init(2014,8,15, new DatePicker.OnDateChangedListener() {public void onDateChanged(DatePicker view, int year,int monthOfYear, int dayOfMonth) {dateEt.setText("您选择的日期是:" + year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");}});timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {timeEt.setText("您选择的时间是:" + hourOfDay + "时" + minute + "分");}});}</span><span style="font-size:18px;">}</span>
效果图:



三、倒计时实现

1,布局文件

(一)设置开始时间  time_out_layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><DigitalClockandroid:id="@+id/myClock"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_margin="10dp"android:textSize="30sp" /><TextViewandroid:id="@+id/text_select"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/myClock"android:layout_centerHorizontal="true"android:text="设置时间"android:textSize="20sp" /><EditTextandroid:id="@+id/minute"android:layout_width="60dp"android:layout_height="80dp"android:layout_alignLeft="@id/myClock"android:layout_below="@id/text_select"android:layout_marginTop="20dp"android:gravity="center"android:inputType="number" /><EditTextandroid:id="@+id/second"android:layout_width="60dp"android:layout_height="80dp"android:layout_below="@id/text_select"android:layout_marginTop="20dp"android:layout_toRightOf="@id/minute"android:gravity="center"android:inputType="number" /><Buttonandroid:id="@+id/button_start"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:gravity="center"android:padding="10dp"android:text="开始倒计时"android:textSize="30sp" />
</RelativeLayout>

(二)展示倒计时效果 start.xml

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/myTime"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_margin="30dp"android:gravity="center"android:textColor="#FF0000"android:textSize="100sp"android:textStyle="bold" />
</LinearLayout></span>
2,实现主类

(一)TimeOutActivity

public class TimeOutActivity  extends Activity {Button startButton;EditText minuteText;EditText secondText;int minute;int second;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.time_out_layout);startButton = (Button) findViewById(R.id.button_start);minuteText = (EditText)findViewById(R.id.minute);secondText = (EditText)findViewById(R.id.second);startButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (!minuteText.getText().toString().equals("")) {minute = Integer.parseInt(minuteText.getText().toString());}if (!secondText.getText().toString().equals("")) {second = Integer.parseInt(secondText.getText().toString());}if (minute != 0 || second != 0) {System.out.println(minute+":"+second);ArrayList<Integer> list = new ArrayList<Integer>();list.add(minute);list.add(second);Intent intent = new Intent(TimeOutActivity.this,StartActivity.class);intent.putIntegerArrayListExtra("times", list);startActivity(intent);}}});}@Overrideprotected void onResume() {minute = 0;second = 0;super.onResume();}}

(二)StartActivity

public class StartActivity extends Activity{static int minute = -1;static int second = -1;TextView timeView;Timer timer;TimerTask timerTask;Handler handler = new Handler(){public void handleMessage(Message msg) {System.out.println("handle!");if (minute == 0) {if (second == 0) {timeView.setText("Time out !");if (timer != null) {timer.cancel();timer = null;}if (timerTask != null) {timerTask = null;}}else {second--;if (second >= 10) {timeView.setText("0"+minute + ":" + second);}else {timeView.setText("0"+minute + ":0" + second);}}}else {if (second == 0) {second =59;minute--;if (minute >= 10) {timeView.setText(minute + ":" + second);}else {timeView.setText("0"+minute + ":" + second);}}else {second--;if (second >= 10) {if (minute >= 10) {timeView.setText(minute + ":" + second);}else {timeView.setText("0"+minute + ":" + second);}}else {if (minute >= 10) {timeView.setText(minute + ":0" + second);}else {timeView.setText("0"+minute + ":0" + second);}}}}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {requestWindowFeature(Window.FEATURE_NO_TITLE);super.onCreate(savedInstanceState);setContentView(R.layout.start);timeView = (TextView)findViewById(R.id.myTime);if (minute == -1 && second == -1) {Intent intent = getIntent();ArrayList<Integer> times = intent.getIntegerArrayListExtra("times");minute = times.get(0);second = times.get(1);}timeView.setText(minute + ":" + second);timerTask = new TimerTask() {@Overridepublic void run() {Message msg = new Message();msg.what = 0;handler.sendMessage(msg);}};timer = new Timer();timer.schedule(timerTask,0,1000);}@Overrideprotected void onDestroy() {if (timer != null) {timer.cancel();timer = null;}if (timerTask != null) {timerTask = null;}minute = -1;second = -1;super.onDestroy();}
}
展示效果:






倒计时例子Demo

      一个小小的提醒,做设计的人不应该和做执行的人多接触;设计要的是天马行空,完美;而做实际的人一直在克服难题,总是在不断超越中。若是可以和设计谈判,那么执行就没有那么背水一战!



这篇关于Android中的倒计时的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1124935

相关文章

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

Android实现悬浮按钮功能

《Android实现悬浮按钮功能》在很多场景中,我们希望在应用或系统任意界面上都能看到一个小的“悬浮按钮”(FloatingButton),用来快速启动工具、展示未读信息或快捷操作,所以本文给大家介绍... 目录一、项目概述二、相关技术知识三、实现思路四、整合代码4.1 Java 代码(MainActivi

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(