本文主要是介绍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中的倒计时的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!