所以我的应用程序应该将用户的输入与应用程序提供的随机引用进行比较,我想将正确的单词用绿色着色,将错误的单词用红色着色。
问题是我不知道如何Spannable
循环使用,尤其是文本总是在变化。
这是代码:
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
}
}
}
这就是我尝试过的:
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 + " ");
}
}
但是生成的文本没有着色,并且它们没有空格地粘合在一起。