如何比较两个EditText字符串然后突出显示Android中的不同之处?

nan*_*r93 1 java arrays android spannablestring

我有2个必须比较的EditText字符串,我知道如何比较并获得“ OK”(如果它们都匹配)和“ NOK”(如果它们不匹配)之类的结果。但是我不知道如何找到不同的字符或部分。举个例子:

EditText editTextStdCode = 18X2101UG1

相比于

EditText editTextActCode = 18Y2101UG1

结果为“ NOK”,因为editTextActCodeeditTextStdCode第18 Y 2101UG1 节中的内容不同,并且我想突出显示字符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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是结果并不准确。请帮忙。

Mr.*_*tel 5

您需要执行一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)