Android实现订单倒计时功能
先上效果图
1.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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="yascn.com.timecalc.MainActivity"> <TextView android:textSize="20dp" android:layout_centerInParent="true" android:id="@+id/tv_remaintime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" /> </RelativeLayout>
2.MainActivity.class
package yascn.com.timecalc; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { TextView tv_remaintime;//倒计时 private long countdownTime;//倒计时的总时间(单位:毫秒) private String timefromServer;//从服务器获取的订单生成时间 private long chaoshitime;//从服务器获取订单有效时长(单位:毫秒) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_remaintime = (TextView) findViewById(R.id.tv_remaintime); getTimeDuring(); } Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { countdownTime -= 1000;//倒计时总时间减1 SimpleDateFormat minforamt = new SimpleDateFormat("mm:ss"); String hms = minforamt.format(countdownTime);//格式化倒计时的总时间 tv_remaintime.setText("还剩下" + hms); handler.postDelayed(this, 1000); } }; private void getTimeDuring() { chaoshitime = 30 * 60 * 1000;//应该从服务器获取 timefromServer = "2017-01-23 11:40:50";//应该从服务器获取 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date serverDate = df.parse(timefromServer); long duringTime = new Date().getTime() - serverDate.getTime();//计算当前时间和从服务器获取的订单生成时间的时间差 countdownTime = chaoshitime - duringTime;//计算倒计时的总时间 handler.postDelayed(runnable, 1000); } catch (ParseException e) { e.printStackTrace(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)