我正在编写一个小型的CountDown程序,我发现其中一个SO链接对我有帮助以获取代码,但我有一个小查询如何在我们提到的倒计时到达时显示消息。
public class MainActivity extends Activity {
String time1 = "14-02-2015 12:01:00";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Calendar start = Calendar.getInstance();
String time = "dd-MM-yyyy hh:mm:ss";
String dateStart =(String) DateFormat.format(time, start);
String dateStop = time1;
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
// Custom date format
java.util.Date d1=null;
java.util.Date d2=null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long diffdays =(diff/ (1000*60*60*24));
long diffHours = ((diff - (1000*60*60*24*diffdays)) / (1000*60*60));
long diffMinutes = (diff - (1000*60*60*24*diffdays) - (1000*60*60*diffHours)) / (1000*60);
long diffSeconds =(diff - (1000*60*60*24*diffdays) - (1000*60*60*diffHours) -(1000*60*diffMinutes))/ (1000);
String out=
"Days: "+diffdays+
" Hours: "+diffHours+
" Minutes: "+diffMinutes+
" seconds: "+diffSeconds;
tv.setText(out);
handler.postDelayed(this, 1000);
}
}, 1000);
}
}
我想要留言"情人节快乐"到达日期时在同一TextView中
答案 0 :(得分:1)
在一起运行倒数计时器不是一个好习惯
如果要设置特定日期,您可能需要在该特定日期添加一些带有自定义消息的警报事件。 此外,你必须编写一个广播接收器来处理该警报,以打开一些活动并在那里处理。
答案 1 :(得分:1)
==============
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your dialog code.
}
});
根据您的申请,您应该这样做。
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your dialog code.
tv.setText(out);
}
});
答案 2 :(得分:0)
你在android中有倒计时:
示例:
CountDownTimer cdt = new CountDownTimer( a.getTime() - b.getTime(), 1000)
{
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
long seconds = millisUntilFinished / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
txtDays.setText( days + "" );
txtHours.setText( hours % 24 + "h" );
txtMinutes.setText( minutes % 60 + "m" );
txtSeconds.setText( seconds % 60 + "s");
}
public void onFinish()
{
// TODO Auto-generated method stub
txtDateTime.setVisibility(View.VISIBLE);
txtDays.setVisibility(View.GONE);
txtHours.setVisibility(View.GONE);
txtSeconds.setVisibility(View.GONE);
txtMinutes.setVisibility(View.GONE);
txtDayText.setVisibility(View.GONE);
}
}.start();