我想比较编辑文本和查看文本,并用绿色突出显示正确的单词,用红色突出显示错误的单词。但是,对于任何正确的单词,此代码会将整个文本着色为绿色,对于任何错误的单词,将整个文本着色为红色。请帮忙..
tview = (TextView) findViewById(R.id.tview);
tview1 = (TextView) findViewById(R.id.tview1);
simpleEditText = (EditText) findViewById(R.id.simpleEditText);
fullStory=tvpass1.getText().toString();
etValue=simpleEditText.getText().toString();
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tview.setText("Time: " + millisUntilFinished / 1000);
tview.setTextColor(Color.BLUE);
}
public void onFinish() {
tview.setText("Time Up!");
tview.setTextColor(Color.RED);
simpleEditText.setEnabled(false);
simpleEditText.clearFocus();
}
}.start();
simpleEditText. addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int count, int before) {
String etValue= simpleEditText. getText().toString();
//text=text.replace("\n", "") ;
String[] EtStArray = etValue.split("\\s+");
String[] VtStArray = fullStory.split("\\s+");
// tview.setText("Words =" +EtStArray.length);
if((EtStArray.length>1) && ( j!=EtStArray.length))
{
// word=EtStArray[i];
if(EtStArray[i].equals(VtStArray[i]))
{
tview1.append(EtStArray[i]+" ");
tview1.setTextColor(Color.GREEN);
}
else
{
tview1.append(EtStArray[i]+" ");
tview1.setTextColor(Color.RED);
}
i++;
j=EtStArray.length;
}
// tview1.setText(etValue);
//tview1.setText(VtStArray[0]);
}
@Override
public void afterTextChanged( Editable s) {
}
}) ;
}
}
最佳答案
您可以像此代码示例一样使用 SpannableStringBuilder
textView = (TextView) findViewById(R.id.textview);
SpannableStringBuilder builder = new
SpannableStringBuilder(textView.getText().toString());
ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);
ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);
ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);
ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);
builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//setSpan(Object what, int start, int end, int flags)
//Mark the specified range of text with the specified object.
textView.setText(builder);
关于更多 https://developer.android.com/reference/android/text/SpannableStringBuilder
关于java - 在 android studio 中突出显示输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303372/