我正在尝试制作倒数计时器。我想出了这段代码,最初我认为它有效。但是,当我运行该应用程序时,发生了两件事,我不知道如何解决...
- 它不同步,虽然它是系统时间和日期,它说只剩下 60 天而不是 61 天,而我知道它是 61!
- 如果我关闭应用程序并返回它会重置计数器...
对此的任何帮助将不胜感激,它不是针对任何特定的个人项目。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView dateBx = (TextView) findViewById(R.id.textView1);
final TextView mTextField = (TextView) findViewById(R.id.mTextField);
final TextView minBx = (TextView) findViewById(R.id.minBx);
final TextView hourBx = (TextView) findViewById(R.id.hourBx);
//set todays date
DateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
//target date
DateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal2 = Calendar.getInstance();
cal2.set(2012,11,25);
//set maths
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
//difference variable
long diff = time2 - time1;
//equations
long diffSec = diff / 1000;
long dMins = diff / (60 * 1000);
long dHour = diff / (60 * 60 * 1000);
long dDay = diff / (24 * 60 * 60 * 1000);
new CountDownTimer(diff, 1000)
{
public void onTick(long millisUntilFinished)
{
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
dateBx.setText("Days remaining: " + millisUntilFinished / (24 * 60 * 60 * 1000));
minBx.setText("Minutes remaining: " + millisUntilFinished / (60 * 1000));
hourBx.setText("hours remaining: " + millisUntilFinished / (60 * 60 * 1000));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
}
我的代码是我在 java 和 android 中学到的一些东西的组合,如果你想出更好的方法来一起做,请告诉我:)
谢谢