2013-11-26 57 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

這是輝煌的。我不斷碰到建議使用自定義處理程序或定時器的人。我確信必須有一種默認的方式來展現時間。謝謝! –

相關問題