packagecom.example.countdown;
importandroid.graphics.Color;
importandroid.os.Handler;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.text.Spannable;
importandroid.text.SpannableString;
importandroid.text.SpannableStringBuilder;
importandroid.text.Spanned;
importandroid.text.style.ForegroundColorSpan;
importandroid.widget.TextView;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
public classMainActivityextendsAppCompatActivity {
privateTextViewtextView;
privateHandlerhandler;
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.tv_time);
handler=newHandler();
handler.postDelayed(runnable,1000);
}
privateRunnablerunnable=newRunnable() {
private longnewTimes;
private longtimes;
privateDatedate;
@Override
public voidrun() {
try{
date=simpleDateFormat.parse("2017年06月30日 17:00:00");
times= System.currentTimeMillis();
newTimes=date.getTime() -times;
newTimes=newTimes/1000;
textView.setText(setTimeStringColor(timeStringLength(newTimes/3600)+"时"+timeStringLength(newTimes/60%60)+"分"+timeStringLength(newTimes%60)+"秒"));
handler.postDelayed(runnable,1000);
}catch(ParseException e) {
e.printStackTrace();
}
}
};
privateString timeStringLength(longtime) {
String time_str = time+"";
if(time_str.length() <2){
time_str ="0"+ time_str;
}
returntime_str;
}
privateSpannableStringBuilder setTimeStringColor(String time) {
SpannableStringBuilder time_str =newSpannableStringBuilder(time);
ForegroundColorSpan one =newForegroundColorSpan(Color.RED);
ForegroundColorSpan two =newForegroundColorSpan(Color.BLACK);
ForegroundColorSpan three =newForegroundColorSpan(Color.RED);
ForegroundColorSpan four =newForegroundColorSpan(Color.BLACK);
ForegroundColorSpan five =newForegroundColorSpan(Color.RED);
ForegroundColorSpan six =newForegroundColorSpan(Color.BLACK);
time_str.setSpan(one,0,2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
time_str.setSpan(two,2,3,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
time_str.setSpan(three,3,5,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
time_str.setSpan(four,5,6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
time_str.setSpan(five,6,8,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
time_str.setSpan(six,8,9,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
returntime_str;
}
}