Spannable无法正常工作

时间:2016-07-30 20:14:07

标签: android

目前我正在开发一个使用TTS来播放字符串的应用程序,而在TTS工作的时候,我有一种方法可以突出显示所说的单词,但是我遇到了Spannable与问号一起工作的问题字符。

如果它有很多问号我的应用程序崩溃了。 如果它只有一个问号,则Spannable会突出显示句子而不是问号。

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void speakText(String text) {
    String regex = "[^.!?\\s][^.!?]*(?:[.!?](?!['\"]?\\s|$)[^.!?]*)*[.!?]?['\"]?(?=\\s|$)";
    Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS).matcher(text);

    auxEnd = 0;
    if (!split.isEmpty()) split.clear();

    while (matcher.find()) {

        split.add(matcher.group()); // add split sentences by ". ? !"

        String utteranceId = this.hashCode() + "";
        tts.speak(matcher.group(), TextToSpeech.QUEUE_ADD, null, utteranceId);
    }
}

@Override
public void onInit(int i) {
    //...
    tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
        @Override
        public void onStart(String utteranceId) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // highlight sentences while tts is working
                    highlight(textViewWordSentence, textView.getText().toString(), split.get(auxEnd));
                    auxEnd++;
                }
            });
        }

        @Override
        public void onDone(String utteranceId) {
            //...
        }

        @Override
        public void onError(String utteranceId) {
            //...
        }
    });
}

private void highlight(TextView textView, String fullText, String textToSearch) {
    SpannableString spannableString = new SpannableString(fullText);
    Matcher matcher = Pattern.compile(textToSearch).matcher(spannableString);

    while (matcher.find()) {
        spannableString.setSpan(new BackgroundColorSpan(Color.CYAN), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    textView.setText(spannableString); // <-- if it has many question marks my app crashes. if it has only a question mark, the Spannable highlight the sentence less the question mark.
}

突出显示方法输出
你好,你在那里? &lt; - Spannable无法突出显示问号
你好,你好吗?&lt; - 我希望这个结果

你好,你好吗? &lt; - 强制关闭

我是初学程序员,我非常感谢您提供的任何帮助。

0 个答案:

没有答案