我有一个工作倒计时,但它只从我输入的硬编码整数开始倒计时。我希望用户能够键入一个数字并让它从该数字开始倒数。我希望将放入“timeedit”的文本放入一个字符串并放入“startTime”的值。
编辑:如果以下代码未在屏幕上正确缩进,您还可以在此处查看代码:http://pastebin.com/BnzEtFX5
代码:
public class TimerActivity extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
public String time;
private long startTime = 30 * 1000;
private final long interval = 1 * 1000;
private EditText timeedit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
timeedit = (EditText) findViewById(R.id.timeedit);
countDownTimer = new MyCountDownTimer(startTime, interval);
time = timeedit.getText().toString();
text.setText(time); //+ String.valueOf(startTime/1000)
}
@Override
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startTime = 30 * 1000;
startB.setText("RESTART");
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
text.setText("Time's up!");
}
@Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
}
}
}
答案 0 :(得分:1)
嗯......我不确定问题是什么,但如果我理解正确,你只需要在onCreate()
String userTime = timeedit.getText().toString();
startTime = Long.parseLong(userTime);
修改
您实际上希望将startTime
和userTime
放入onClick
。如果它在onCreate()
中,那么除非您在xml中设置了默认值,否则您的EditText
将为空,但无论哪种方式,它都不会是用户输入的内容。如果用户输入数字字符以外的内容,您还需要使用try/catch
进行环绕。
public void onClick(View v) {
String userTime = timeedit.getText().toString();
long startTime = Long.parseLong(userTime);
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP")
答案 1 :(得分:0)
如果您想让用户做一些输入,您只需要通过以下方式获取:
String userCountDown = timeEdit.getText().toString();
然后将其解析为Long:
long userStartTime = Long.parseLong(userCountDown);
然后,将其传递给countDown
countDownTimer = new MyCountDownTimer(UserStartTime, interval);
但是你必须确保timeEdit中的值是Long值。通过将layout.xml文件中的属性inputType =“number”设置为R.id.timeedit,您可以确保获得Long。但是要确保有输入,您可以进行任何检查并向用户显示警告。
if (!timerHasStarted) {
String userCountDown = timeEdit.getText().toString();
if(userCountDown.length()<1){
Toast.makeText(yourActivity.this,"PLEASE DO SOME INPUT",Toast.LENGTH_LONG).show();
}else{
long userStartTime = Long.parseLong(userCountDown);
countDownTimer = new MyCountDownTimer(userStartTime, interval);
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
}
} else {
countDownTimer.cancel();
timerHasStarted = false;
startTime = 30*1000;
startB.setText("RESTART");
}