Skip to content Skip to sidebar Skip to footer

Android Edittext Highlight Multiple Words In The Text

I have searched some words in the text of a EditText. After some logic, I get the index of these words. The indices are stored in an arrayList>. Then I used this function to h

Solution 1:

it seems to be correct, but it is better to replace your code with

publicvoidchangeColor(EditText et, ArrayList<ArrayList<Integer>> arr) {
    Spannable wordtoSpan = new SpannableString(et.getText());
    if (arr==null) return;
    for (int i=0; i<arr.size(); i++){
        wordtoSpan.setSpan(new BackgroundColorSpan(Color.BLUE), arr.get(i).get(0),
            arr.get(i).get(1), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        System.out.println("i'm changing color now");
    }
    et.setText(wordtoSpan);
}

if after this changes, your problem remains yet, i think it might be related to your string indices in "arr"

Solution 2:

I am not sure but it may happen due to the behavior of edit text and textview with for or while loop. You can't achieve such behavior with for loop. I was trying to do the same for a Karaoke app, and was finally able to do this using runnable and handler. Try to use the following code.

   `Stringtext= yourEditText.getText().toString();
    final String[] wordArray = text.split(" ");
    finalHandlerhandler=newHandler();
    final String[] selString = newString[1];
    Runnablerunnable=newRunnable() {
        int i=0;
        @Overridepublicvoidrun() {
            selString[0] = wordArray[i];
            i++;
            Stringstr=  et.getText().toString().replaceAll(selString[0], "<font color='red'>"+ selString[0] +"</font>");
            ((EditText)et).setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
            if(i<wordArray.length)
                handler.postDelayed(this,500);
        }
    };
    handler.post(runnable);`

The code gets the text entered in edit text by user, split it using space, and highlight words one by one with a time gap of 500 milis.

Solution 3:

That is what i am using.

publicvoidsetHighLightedText(EditText editText, String textToHighlight) {
    Stringtvt= editText.getText().toString();
    intofe= tvt.indexOf(textToHighlight, 0);
    SpannableWordtoSpan=newSpannableString(editText.getText());

    for (intofs=0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {


        ofe = tvt.indexOf(textToHighlight, ofs);
        if (ofe == -1)
            break;
        else {
            WordtoSpan.setSpan(newBackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            editText.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
        }
    }
}

Post a Comment for "Android Edittext Highlight Multiple Words In The Text"