So my app should compare the user's input with a random quote provided by the app, and I want to color the correct word with green and the wrong one with red.
the problem is that I don't know how to do it with Spannable
in a loop, and especially that the text is always changing.
This is the code:
if(quoteWords.length == resultWords.length){
for(int i = 0; i < quoteWords.length; i++) {
if (quoteWords[i].equals(resultWords[i])) {
//color the word with green
} else {
//color the word with red
}
}
}
And this is what I tried:
if(quoteWords.length == resultWords.length){
SpannableStringBuilder fullStyledSentence = new SpannableStringBuilder();
ForegroundColorSpan correctColor = new ForegroundColorSpan(Color.GREEN);
ForegroundColorSpan wrongColor = new ForegroundColorSpan(Color.RED);
int start;
for(int i = 0; i < quoteWords.length; i++) {
start = fullStyledSentence.length(); //get length of current SpannableString
fullStyledSentence.append(quoteWords[i]);
if (quoteWords[i].equals(resultWords[i])) { //color each word using its length
fullStyledSentence.setSpan(correctColor, start, start + quoteWords[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.i("AzureSpeechRecognition", "word number " + i + "is correct");
} else {
fullStyledSentence.setSpan(wrongColor, start, start + quoteWords[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.i("AzureSpeechRecognition", "word number " + i + "is wrong");
}
mQuoteBodyTextView.setText(null); //to delete repeatedly appended text
mQuoteBodyTextView.append(fullStyledSentence + " ");
}
}
But the resulted text isn't colored and they are glued together with no spaces.