2013-11-26 122 views
0

我有一个简单的应用程序,用于编写应用程序启动时显示的句子。唯一的问题是,我需要应用程序来计算用户编写句子所用的时间..就像您触摸“提交”按钮Toast消息会说“That's Right!,它花了你3.2秒”作为例子。Android SDK(Eclipse):如何为一个简单的应用程序创建一个简单的计时器?

我听说您可以设置一个计时器,以便在发生特定操作时启动...并且您可以命令它停止。

让我们来说说,定时器将在您启动应用程序时开始,当您点击“提交”按钮时,定时器将停止,并提供上面的敬酒信息,计算开始后编写知识的确切时间App! *

这里是应用程序代码希望它可以帮助:*

Button w; 

TextView t; 

EditText e; 

@Override 

protected void onCreate(Bundle savedInstanceState) { 

super.onCreate(savedInstanceState); 

setContentView(R.layout.activity_main); 



w = (Button) findViewById(R.id.Write); 

t= (TextView) findViewById(R.id.FTS); 

e = (EditText) findViewById(R.id.Text); 


w.setOnClickListener(new View.OnClickListener() { 

@Override 

public void onClick(View v) { 


String check1 = t.getText().toString(); 
String check2 = e.getText().toString(); 

if (check1.equals(check2)) 

    Toast.makeText(MainActivity.this,"You Wrote it Right !!!",Toast.LENGTH_LONG).show(); 

else if (check2.equals("")) 

Toast.makeText(MainActivity.this,"It's Empty",Toast.LENGTH_LONG).show(); 

else 
    Toast.makeText(MainActivity.this,"You wrote it wrong,try again !",Toast.LENGTH_LONG); 

我完全新的到Android,所以我真的不知道该怎么做了,感谢您的时间。 *

回答

11

您可以使用Timer类启动计时器会话。遵循以下步骤:

1-定义Timer和可变的全局变量来计算,如时间:

private Timer t; 
private int TimeCounter = 0; 

2-活动开始然后当,所以在onCreate添加以下内容:PS :我做的是我有一个textView来显示他在写句子时的时间。所以,如果你不想,你可以在下面的代码

t = new Timer(); 
    t.scheduleAtFixedRate(new TimerTask() { 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      runOnUiThread(new Runnable() { 
       public void run() { 
        tvTimer.setText(String.valueOf(TimeCounter)); // you can set it to a textView to show it to the user to see the time passing while he is writing. 
        TimeCounter++; 
       } 
      }); 

     } 
    }, 1000, 1000); // 1000 means start from 1 sec, and the second 1000 is do the loop each 1 sec. 

删除tvTimer部分则单击该按钮时,停止计时,并显示在ToasttimeCounter varaible。

t.cancel();//stopping the timer when ready to stop. 
Toast.makeText(this, "The time taken is "+ String.valueOf(TimeCounter), Toast.LENGTH_LONG).show(); 

P.S:你必须处理秒转换为分钟,因为这样你就需要将它转换到6分钟的数量可能扩展到360秒。你可以在t.schedualeAtFixedRate或完成后将它转换并显示在烤面包上

希望你发现这个很有用。请给我一个反馈,如果它为你工作。

+1

非常感谢! ,它完美的作品:) –

+0

很高兴我能够帮助你 – Coderji

6

让我将你的注意力到Chronometer Widget on the Dev Page

而且,这里有一个你会使用的Widget精密计时器得到什么风味(跳到8:30)

Video of Chronometer Widget

XML

<Chronometer 
    android:id="@+id/chronometer1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

Java

((Chronometer) findViewById(R.id.chronometer1)).start(); 
((Chronometer) findViewById(R.id.chronometer1)).stop(); 
+0

这是辉煌的。我不断碰到建议使用自定义处理程序或定时器的人。我确信必须有一种默认的方式来展现时间。谢谢! –

相关问题