gpt4 book ai didi

java - 在循环中对可变文本使用 spannable

转载 作者:行者123 更新时间:2023-12-04 09:01:21 26 4
gpt4 key购买 nike

所以我的应用程序应该将用户的输入与应用程序提供的随机引用进行比较,我想用绿色为正确的单词着色,用红色着色错误的单词。
问题是我不知道如何使用 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 + " ");
}

}
但结果文本没有着色,它们被粘在一起,没有空格。

最佳答案

看来ForegroundColorSpan/BackgroundColorSpan不可重用,每次我们都应该实例化一个新的。无论如何,我认为使用 SpannableString 写它更有意义。像下面这样:

public class MainActivity extends AppCompatActivity {

// replacing all whitespaces with single space
private String quote = "I want to color the correct word with green".replaceAll("\\s+", " ");
private String result = "I want to color the right word with blue".replaceAll("\\s+", " ");

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String[] quoteWords = quote.split("\\s");
String[] resultWords = result.split("\\s");

SpannableString spannableQuote = new SpannableString(quote);

if (quoteWords.length == resultWords.length) {
int index = 0;
for (int i = 0; i < quoteWords.length; i++) {
spannableQuote.setSpan(
new BackgroundColorSpan(quoteWords[i].equals(resultWords[i]) ? Color.GREEN : Color.RED),
index,
index + quoteWords[i].length(),
SpannableString.SPAN_INCLUSIVE_INCLUSIVE
);
index += quoteWords[i].length() + 1; // 1 for the space between words
}
}

((TextView) findViewById(R.id.textView1)).setText(result);
((TextView) findViewById(R.id.textView2)).setText(spannableQuote);
}
}

结果:

关于java - 在循环中对可变文本使用 spannable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63552706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com