【问题标题】:How to countdown days in android application?如何在android应用程序中倒计时?
【发布时间】:2014-04-05 11:36:17
【问题描述】:

最后一天我尝试创建一个倒计时还剩 77 天。我做到了,但问题是我的倒计时是以毫秒为单位的,而以毫秒为单位的 77 天正好是 6652800000,问题是如果我用这个值设置我的倒计时,它会显示一个错误,上面写着:文字 6652800000 int 类型超出范围。如何正确设置从现在倒计时到未来77天?谢谢!

这是我的:

MainActivity:

package com.example.dasds;


import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;


public class MainActivity extends Activity {
TextView tv; //textview to display the countdown
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
this.setContentView(tv);
//5000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(6652800000,86400000);
counter.start();
}
//countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv.setText("Done");
}
@Override
public void onTick(long millisUntilFinished) {
tv.setText("Left: " + millisUntilFinished/86400000);
}
}
}

【问题讨论】:

  • 查看 Java 原始类型 here。在您的情况下,long 就足够了。
  • 又该如何改变呢?
  • 您也可以尝试使用 Joda 时间库,它会计算天数而不是时间。
  • 我看不出您是如何声明整数变量的。你能把它们贴出来让我告诉你在哪里改变吗?通常,millisUntilFinished 可能需要声明为 long
  • 但是这里设置为long:public MyCount(long millisInFuture, long countDownInterval)

标签: android countdown days


【解决方案1】:

在数字文字后键入L,将其转换为long

MyCount counter = new MyCount(6652800000L,86400000L);

【讨论】:

  • 太完美了。工作完美。非常感谢!
【解决方案2】:

在调用 MYCount 构造函数时尝试将参数值转换为 long。

【讨论】:

  • 你建议怎么做?
  • MyCount 计数器 = new MyCount(6652800000L,86400000L);
【解决方案3】:
int year = Integer.parseInt(year);
int month = Integer.parseInt(monthafter77days);
int day = 
Integer.parseInt(dateafter77days);
int hour = Integer.parseInt(hourneeded if );
int minute = Integer.parseInt(minuteneeded if);
GregorianCalendar calendar = new GregorianCalendar(year, month, day, hour, minute);
/**
* Converting the date and time in to
* milliseconds elapsed since epoch
*/
long alarm_time = calendar.getTimeInMillis();
schedulealarm(alarm_time );

享受

【讨论】:

  • 我不知道如何更改它。也许你可以更具体一点?谢谢!
【解决方案4】:

尝试如下改变你的 onTick 方法。 Android textviews 在传递 double 和 long 值时往往会搞砸。

 public void onTick(long millisUntilFinished) {
    tv.setText("Left: " + String.valueof(millisUntilFinished/86400000));
}

【讨论】:

  • 一天的值没有错,问题是77天的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多