如何改变一个TextView每一秒在Android中 [英] How to change a TextView every second in Android

查看:130
本文介绍了如何改变一个TextView每一秒在Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的Andr​​oid音乐播放器。我想有一个TextView,显示当前时间在歌曲分:秒格式。所以,我想的第一件事是,使活动的Runnable,并把这个在run():

  INT位置= 0;
而(MPService.getMP()= NULL和放大器;!&安培;位置< MPService.duration){
尝试 {
    视频下载(1000);
    位置= MPService.getSongPosition();
}赶上(InterruptedException异常E){
    返回;
}

// ...转换位置格式化分:秒串...

currentTime.setText(时间); // currentTime的=(的TextView)findViewById(R.id.current_time);
 

但是,失败,因为我只能摸一个TextView在其中创建线程。于是我试着用runOnUiThread(),但是,这并不工作,因为那时视频下载(1000)是在主线程中反复调用,因此该活动只是挂在空白屏幕。因此,任何想法如何,我可以解决这个问题?


新的code:

 私人诠释的startTime = 0;
私人处理程序timeHandler =新的处理程序();
私人Runnable接口录入=新的Runnable(){
    公共无效的run(){
        最终诠释开始= startTime时;
        INT米利斯= appService.getSongPosition() - 启动;
        INT秒=(int)的((米利斯/ 1000)%60);
        INT分钟=(int)的((米利斯/ 1000)/ 60);
        Log.d(秒,Integer.toString(秒)); //这里没有问题
        如果(秒-1,10){
            //这个被击中,但文从来没有从0:00原值改变
            currentTime.setText(的String.Format(%D:0%D,分,秒));
        } 其他 {
            currentTime.setText(的String.Format(%D:%D,分,秒));
        }
        timeHandler.postAtTime(此,(((分钟* 60)+秒+ 1)* 1000));
    }

};

私人ServiceConnection onService =新ServiceConnection(){
公共无效onServiceConnected(组件名类名,
        的IBinder rawBinder){
      AppService服务=((MPService.LocalBinder)rawBinder).getService();

    //开始播放歌曲等。

    如果(startTime时== 0){
        的startTime = appService.getSongPosition();
        timeHandler.removeCallbacks(录入);
        timeHandler.postDelayed(录入,1000);
    }
}
 

解决方案

使用定时器本(而不是,而在里面循环使用 Thread.sleep代码)。请参阅本文的如何使用定时器来定期更新UI元素的例子:

从计时器更新UI

修改:路回更新的链接,这要归功于 Arialdo :<一href="http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html" rel="nofollow">http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html

编辑2 :路回非链接,感谢 gatoatigrado http://android-developers.blogspot.com/2007/11/stitch-in-time.html

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 the activity Runnable and put this in run():

int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
    Thread.sleep(1000);
    position = MPService.getSongPosition();
} catch (InterruptedException e) {
    return;
}

// ... convert position to formatted minutes:seconds string ...

currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);

But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?


new code:

private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
    public void run() {
        final int start = startTime;
        int millis = appService.getSongPosition() - start;
        int seconds = (int) ((millis / 1000) % 60);
        int minutes = (int) ((millis / 1000) / 60);
        Log.d("seconds",Integer.toString(seconds)); // no problem here
        if (seconds < 10) {
            // this is hit, yet the text never changes from the original value of 0:00
            currentTime.setText(String.format("%d:0%d",minutes,seconds));
        } else {
            currentTime.setText(String.format("%d:%d",minutes,seconds));
        }
        timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
    }

};

private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
        IBinder rawBinder) {
      appService = ((MPService.LocalBinder)rawBinder).getService();

    // start playing the song, etc. 

    if (startTime == 0) {
        startTime = appService.getSongPosition();
        timeHandler.removeCallbacks(updateTime);
        timeHandler.postDelayed(updateTime,1000);
    }
}

解决方案

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

这篇关于如何改变一个TextView每一秒在Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆