使用CountDownTimer添加样式每隔几毫秒一个正确的做法? [英] is using CountDownTimer to add styles every few milliseconds a correct approach?

查看:158
本文介绍了使用CountDownTimer添加样式每隔几毫秒一个正确的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个音轨播放和单词的每个单词都有相应的起始时间轨迹数组:

I have an audio track playing and the array of words in the track where each word has corresponding starting time:

HashMap<String, Float> words = new HashMap<>();
words.put("This", 11.258);
words.put("is", 11.733);
words.put("some", 11.733);

我也有一个TextView显示该文本。每当一个字,在音频轨发音,我想这个词高亮显示。此刻,我能想到的唯一解决办法是那里运行 CountDownTimer 每隔几毫秒,并突出显示当前播放的话,是这样的:

I also have this text displayed in a TextView. Whenever a word is pronounced in the audio track, I want that word highlighted. At the moment the only solution I can think of is to run CountDownTimer every few milliseconds and highlight currently played word there, something like this:

 new CountDownTimer(30000, 4) {

     public void onTick(long millisUntilFinished) {
        // remove previos word highlighting
        ...
        // highlight current word
        Spannable spannableText = new SpannableString(tv.getText());
        spannableText.setSpan(new BackgroundColorSpan(Color.LTGRAY), startOffset, endOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(spannableText);
     }

     public void onFinish() {

     }
  }.start();

这是方法确定或可能有实现我所描述的功能更好的方法?也许使用的东西从MediaPlayer的?

Is this approach OK or maybe there are better approaches to implement the functionality I described? Maybe using something from MediaPlayer?

推荐答案

您不必定义自己的线程定时器,所以你
回避线程管理的所有问题,让系统处理它。

You do not have to define your own thread for the Timer, so you sidestep all the issues of thread management, letting the system handle it.

下面是处理程序执行:

    //updated the screen when we are testing for connectivity and errors.
private Handler handlerHighlightWords = new Handler() {
    @Override
    public void handleMessage(Message msg) {

                ...
        // highlight current word
        Spannable spannableText = new SpannableString(tv.getText());
        spannableText.setSpan(new BackgroundColorSpan(Color.LTGRAY), startOffset, endOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(spannableText);
        handlerMessageText.sendEmptyMessageDelayed(0, 1000);
    }
};

    //runnable to to feed to handler.
final Runnable handlerRunnableMessage = new Runnable() {
    public void run() {
        Spannable spannableText = new SpannableString(tv.getText());
        spannableText.setSpan(new BackgroundColorSpan(Color.LTGRAY), startOffset, endOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(spannableText);


    }
};

然后,一旦你点击一个按钮:

Then once you click a button:

handlerMessageText.post(handlerRunnableMessage);

这篇关于使用CountDownTimer添加样式每隔几毫秒一个正确的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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