我有一个音轨和轨道中的单词数组,每个单词都有相应的开始时间:
HashMap<String, Float> words = new HashMap<>();
words.put("This", 11.258);
words.put("is", 11.733);
words.put("some", 11.733);
我也在TextView中显示了这个文本。每当在音轨中发音时,我都希望突出显示该单词。目前,我能想到的唯一解决方案是每隔几毫秒运行CountDownTimer
并突出显示当前播放的单词,如下所示:
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中的东西?
答案 0 :(得分:1)
您不必为Timer定义自己的线程,所以你 回避线程管理的所有问题,让系统处理它。
这是处理程序实现:
//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);
}
};
然后点击按钮后:
handlerMessageText.post(handlerRunnableMessage);