我有 2 个 EditText 字符串需要进行比较,我知道如何比较并得到类似“OK”(如果它们都匹配)和“NOK”(如果它们不匹配)这样的结果。 但我不知道如何找到不同的字符或部分。 例如:
EditText editTextStdCode = 18X2101UG1
比较
EditText editTextActCode = 18Y2101UG1
结果是“NOK”,因为 editTextActCode
与 section 18Y2101UG1 中的 editTextStdCode
不同,我想突出显示字符 Y因为它与 editTextActCode
不同。
我尝试过使用 SpannableString,如下所示:
private void highlightChar(Integer startSpan, Integer endSpan) {
SpannableString spannableStr = new SpannableString(editTextActCode.getText().toString());
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.GREEN);
spannableStr.setSpan(backgroundColorSpan, startSpan, endSpan, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
editTextActCode.setText(spannableStr);
}
/**
*
* @param editText
* @param fIndex
* @param lIndex
* @param textToHighlight
*/
public void setHighLightedText(EditText editText, Integer fIndex, Integer lIndex, String textToHighlight) {
String tvt = editText.getText().toString().substring(fIndex,lIndex);
int ofe = tvt.indexOf(textToHighlight);
Spannable wordToSpan = new SpannableString(editText.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
但结果并不准确。请帮忙。
最佳答案
您需要执行一个 for 循环,然后获取各个字符串字符并进行比较:
StringBuilder sbedtstdcode = new StringBuilder();
StringBuilder sbedtactcode = new StringBuilder();
String editTextStdCode = editTextStdCode.getText().toString();
String editTextActCode = editTextActCode.getText().toString();
for (int i = (editTextStdCode.length - 1); i >= 0; i--)
{
String stdstr = editTextStdCode.charAt(i);
String actstr = editTextActCode.charAt(i);
if(stdstr.equals(actstr))
{
sbedtstdcode.append(stdstr.charAt(i));
sbedtactcode.append(actstr.charAt(i));
}
else
{
Spannable spactstr = new SpannableString(actstr);
actstr.setSpan(new ForegroundColorSpan(Color.BLUE),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.append(spactstr);
}
}
关于java - 如何比较两个 EditText 字符串然后在 Android 中突出显示不同之处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57470405/