Highlight a part of textview in android dynamically [closed]

I have to do a karaoke interface. I need to highlight a part of the text view from time to time. let’s say 5 seconds. I have separated the lines by “n”. After 5 sec, I need to highlight the other sent of lines till it meets “n”.

Answer

Steps to highlight substring of String in textview:

  1. Split String to substring.
  2. Add Loop on substring array length.
  3. Add delay in loop – Need to add text highlight login under this delay.

Please try below code:

    TextView  tvHighLightText = findViewById(R.id.tvHighLightText);
    String textStr = "In publishing and graphic design," +
            " nLorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document" +
            " nor a typeface without relying on meaningful content. " +
            "n Lorem ipsum may be used as a placeholder before final copy is available.";
    tvHighLightText.setText(textStr);
    String splitStr[] = textStr.split("n");
    Log.e("splitStr---",""+splitStr.length);
    Handler handler1 = new Handler();
    for(int i = 0; i<splitStr.length; i++){
        int finalI = i;
        handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                Spannable spannableString = new SpannableString(textStr);
                int startingPosition = textStr.indexOf(splitStr[finalI]);
                int endingPosition = startingPosition + splitStr[finalI].length();
                // For highlight current selected Sub String
                spannableString.setSpan(new ForegroundColorSpan(Color.MAGENTA), startingPosition, endingPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                // For de-colorize the part of a string that has been colorized before
                spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, startingPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvHighLightText.setText(spannableString);
            }
        }, 5000 * i);
    }

You can change delay time according to your requirment.

Edit:

Add this code in handler under loop for de-colorize the part of a string that has been colorized before.

spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, startingPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);