我刚开始使用Android SDK进行编码,这是我第一次尝试使用倒数计时器。我已经将计时器设置为在按下按钮时启动setOnClickListener()。单击按钮时,计时器无法启动,但应用程序停止工作。设备会显示一条消息,指出应用已停止运行。
我写了一个方法将时间格式化为分钟和秒。我已经在CountDownTimer的onTick()方法中设置了调用。
我在下面发布了我的代码。请看一下,然后指出问题出在哪里以及做什么。非常感激。
package com.example.day1;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView Timer;//Textview to display the timer
//This is the method to format the time into minutes and seconds
public String formatTime(long millis)
{
String output="00:00";
long second=millis/1000;
long minute=second/60;
second=second%60;
minute=minute%60;
String sec=String.valueOf(second);
String min=String.valueOf(minute);
output=min+":"+sec;
return output;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown);
Timer=(TextView) findViewById(R.id.text1);
Button button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new CountDownTimer(60000,1000)
{
public void onTick(long millisUntilFinished){
Timer.setText(formatTime(millisUntilFinished));
}
public void onFinish()
{
onStop();
}
}.start();
}
});
}
}
答案 0 :(得分:1)
(1)您的应用崩溃是因为您没有使用OnClickListener实现您的活动:您需要扩展您的活动方法onclicklistener evet
这是代码
package com.example.day1;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
///////////////////The solution is fix here///////////////
public class MainActivity extends Activity implements View.OnClickListener {
///////////////////End of solution//////////
TextView Timer;//Textview to display the timer
//This is the method to format the time into minutes and seconds
public String formatTime(long millis)
{
String output="00:00";
long second=millis/1000;
long minute=second/60;
second=second%60;
minute=minute%60;
String sec=String.valueOf(second);
String min=String.valueOf(minute);
output=min+":"+sec;
return output;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown);
Timer=(TextView) findViewById(R.id.text1);
Button button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new CountDownTimer(60000,1000)
{
public void onTick(long millisUntilFinished){
Timer.setText(formatTime(millisUntilFinished));
}
public void onFinish()
{
onStop();
}
}.start();
}
});
}
}