2016-04-17 45 views
0

假設我有一個計時器,它在片段A中使用TextView。我想在片段B中使用此計時器。我該怎麼做?這是在片段A被用來設置定時器的代碼...我如何將一個計時器從一個片段傳遞到另一個片段?

private Runnable mUpdateTimeTask = new Runnable() { 
    public void run() { 
     long totalDuration = mp.getDuration(); 
     long currentDuration = mp.getCurrentPosition(); 

     // Displaying total duration time 
     songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); 
     // Displaying current time 
     songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); 

     // Running this thread after 100 milliseconds 
     mHandler.postDelayed(this, 100); 
    } 
}; 

現在我想用一個與該songCurrentDurationLabel TextView的關聯,在片段B以及定時器。

我該如何解決這個問題?

謝謝!

+0

你不應該從你的主線程以外更新你的UI。 – dazito

+0

你能解釋一下嗎? –

+0

檢查這個問題的解釋:http://stackoverflow.com/questions/4369537/update-ui-from-thread *但*不使用AsyncTask,你將在稍後遇到問題(如內存泄漏,當你旋轉設備)。在這裏閱讀更多關於它的信息:http://simonvt.net/2014/04/17/asynctask-is-bad-and-you-should-feel-bad/ – dazito

回答

0

在主機Activity中使用計時器,並將回調設置/發佈結果作爲回調。 Android UI工具包不是線程安全的 - 不要從UI線程外部訪問UI。

查看一些gotchas

相關問題