How to change a TextView every second in Android

后端 未结 5 860
庸人自扰
庸人自扰 2020-12-10 02:52

I\'ve made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make

相关标签:
5条回答
  • 2020-12-10 03:13

    I think the below blog article clearly gives a very nice solution. Especially, if you are a background service and want to regularly update your UI from this service using a timer-like functionality. It really helped me, much more than the 2007 blog link posted by MusiGenesis above.

    https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/

    0 讨论(0)
  • 2020-12-10 03:17

    what about this:

        int delay = 5000; // delay for 5 sec.
        int period = 1000; // repeat every sec.
    
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask()
            {
                public void run()
                {
                    //your code
                }
            }, delay, period);
    
    0 讨论(0)
  • 2020-12-10 03:21

    You have to use a handler to handle the interaction with the GUI. Specifically a thread cannot touch ANYTHING on the main thread. You do something in a thread and if you NEED something to be changed in your main thread, then you call a handler and do it there.

    Specifically it would look something like this:

    Thread t = new Thread(new Runnable(){ ... do stuff here

    Handler.postMessage(); }

    Then somewhere else in your code, you do

    Handler h = new Handler(){

    something something... modify ui element here }

    Idea its like this, thread does something, notifies the handler, the handler then takes this message and does something like update a textview on the UI thread.

    0 讨论(0)
  • This is one more Timer example and I'm using this code in my project. https://stackoverflow.com/a/18028882/1265456

    0 讨论(0)
  • 2020-12-10 03:34

    Use a Timer for this (instead of a while loop with a Thread.Sleep in it). See this article for an example of how to use a timer to update a UI element periodically:

    Updating the UI from a timer

    Edit: updated way-back link, thanks to Arialdo: http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html

    Edit 2: non way-back link, thanks to gatoatigrado: http://android-developers.blogspot.com/2007/11/stitch-in-time.html

    0 讨论(0)
提交回复
热议问题