currently I'm working on an app that uses the TTS to play some strings and while the TTS works, I have a method to highlight the word being spoken, but I have problems with Spannable to works with the question mark character.
If it has many question marks my app crashes. If it has only a question mark, Spannable highlight the sentence but not the question mark.
@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.
}
highlight method output
Hello are you there? <-- Spannable cannot highlight the question mark
Hello are you there? <-- I wish this result
Hello are you there??? <-- force close
I'm a beginner programmer and I really appreciate any help you can provide.