1

I add a text like this:

tv.setText("This is text created with StringBuilder");

Then I track which word a user longclicks on, and want to highlight that word for some short period of time:

tv.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        int offset = tv.getOffsetForPosition(coordinates.get(0), coordinates.get(1));
        int[] offsets = getWordOffsets(text.toString(), offset);
        int startOffset = offsets[0];
        int endOffset = offsets[1];

        // here I want to highlight the word starting from startOffset to endOffset

I've read that I should use SpannableString, however most examples show that I should created new SpannableString using the entire text, and then I can add styles to part of it. Is there any way to make part of the text in TextView spannable? Or should I create new SpannableString strings from TextView content and set spans every time the long click event is triggered?

Msk
  • 857
  • 9
  • 16
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • `Or should I create new SpannableString strings from TextView content and set spans every time the long click event is triggered`, yes you have to – Blackbelt May 04 '15 at 09:00
  • I see, thanks, how's this solution in terms of perfomance? I have about 1000 words in my TextView. Maybe there's a better alternative to this approach? – Max Koretskyi May 04 '15 at 09:04

1 Answers1

1

you can use some countdown timer

 //___ HIGHLIGHT HERE ______
    new CountDownTimer(500,500){

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            //___ UN HIGHLIGHT HERE ______

        }
    }.start();

and for the highlight you can use something like

textView.setText(Html.fromHtml("<font color='#FF0000'>text</font>"));
OWADVL
  • 10,704
  • 7
  • 55
  • 67
  • thanks, I actually don't need to hide it within 5 seconds, I need to hide it when dialog closes, I made this task up for example, the question is about highlighting part of the string. I'll upvote for the new method `CountDownTimer` I didn't know :) And how to use `Html.fromHtml` with the other string? As you outlined it'll highlight entire text, not one word – Max Koretskyi May 04 '15 at 09:31
  • mmm... you can highlighted textunhihlightedtextgreen highlighted and so on. It's just like html and css on the web – OWADVL May 04 '15 at 09:34
  • yeah, but that's still is almost equivalent to creating spannable strings as I'd have to replace TextView content every time the word is longclicked. – Max Koretskyi May 04 '15 at 09:38