簡體   English   中英

Java for Android計時器

[英]Java for Android timer

你能告訴我這行的問題在哪里嗎: timerText.setText(seconds);

public class ShowTimer extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_test_xml);

        Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            int seconds;
            TextView timerText = (TextView) findViewById(R.id.TimerTestId);
            @Override
            public void run() {
                seconds++;
                timerText.setText(seconds);
            }
        }, 0, 1000);

    }}

我認為您要在文本視圖中顯示seconds 但是, TextView.setText(int)函數不會執行此操作(實際上我不確定該執行的操作)。 您想要做的是timerText.setText(""+seconds); 將參數轉換為字符串並將函數調用更改為其他重載函數。

seconds是一個int ,而我認為您希望按照文檔中的字符序列或通過資源ID引用一個字符進行傳遞。

盡管這不能回答OP的原始問題,但此線程中介紹了替代方法(並且-如果您同意Android文檔的建議-更好)。

與Richard的建議一樣,您的另一個問題是在非UI線程上更新TextView,因此請考慮使用Handler

public class ShowTimer extends Activity {

    private Handler mHandler;
    private TextView timerText = null;
    private int seconds;

    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            timerText.setText(String.valueOf(seconds++));
            mHandler.postDelayed(timerRunnable, 1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_test_xml);

        mHandler = new Handler();

        timerText = (TextView) findViewById(R.id.TimerTestId);
        timerRunnable.run();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM