2016-03-23 52 views
0

我需要在一個時間間隔內收集數據,這裏的數據收集是用計數整數模擬的。我似乎無法收集該整數,但。我需要集合在單擊按鈕後啓動,並在單擊另一個時結束。有任何想法嗎?如何在Android中使用計時器?

package com.example.test.gothedistance; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

import java.util.Timer; 
import java.util.TimerTask; 

public class MainActivity extends AppCompatActivity { 

Button start, stop; 
TextView sumText; 
int count; 
Timer t; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    start = (Button) findViewById(R.id.startButton); 
    stop = (Button) findViewById((R.id.stopButton)); 
    sumText = (TextView) findViewById(R.id.sumTV); 
    t = new Timer(); 
    count = 0; 




    t.scheduleAtFixedRate(
      new TimerTask() 
      { 
       public void run() 
       { 
        count++; 

       } 
      },0,2000); 

    stop.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      t.cancel(); 
      sumText.setText(count); 
     } 
    }); 
} 
} 
+0

我認爲您正在尋找類似以下的內容:http://android-er.blogspot.com.es/2013/12/example-of- using-timer-and-timertask-on.html希望它有幫助! –

+1

我也會說,定時器通常不會在Android中使用,通常是它的警報或處理程序的延遲消息。 –

回答

1

的問題是可能會與線sumText.setText(count),它使用TextView.setText(int resid)。這意味着它正在尋找一個等於count的ID,而不是顯示count的值。您需要將此值首先轉換爲整數:

sumText.setText(Integer.toString(count)) 
+0

哦jeez,這很令人尷尬(我一直在使用一種會自動處理這個問題的語言:b) –

相關問題