21
votes

Is it possible to Highlight text in a TextView or WebView?

I see it is possible in a EditText

Highligh text in a EditText

I'd like to do the same in TextView or WebView.
Thats Possible?

4
What's the way to do it in a webview?AnupamChugh

4 Answers

61
votes

enable TextView's Spannable storage! by default Spannable storage in EditText is true.

so

TextView myTV = (TextView)findViewById(R.id.textView1);
String  textString = "StackOverFlow Rocks!!!"; 
Spannable spanText = Spannable.Factory.getInstance().newSpannable(textString);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTV.setText(spanText);
1
votes

As well you could use this one solution for WebView. Call findAllAsync

webview.findAllAsync(((EditText) findViewById(R.id.edit)).getText().toString());

than add FindListener to WebView

    webview.setFindListener(new FindListener() {

        @Override
        public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
            Toast.makeText(getApplicationContext(), "Matches: " + numberOfMatches, Toast.LENGTH_LONG).show();
        }
    });

Iterate in result with webview.findNext(false); where false/true shows the direction.

But this solution was added in API level 16!!! Instead of you can setup JavaScript for higlihting - http://www.nsftools.com/misc/SearchAndHighlight.htm

0
votes

For TextView

You can use textView.setTextIsSelectable(true) in your activity or fragment or adapter.

-1
votes

Actually, you do not have to develop this feature by yourself. You just need to use EditText instead TextView, while you set the android:editable of EditText to false.

My answer is here, hope it may help you:

https://stackoverflow.com/a/11026292/966405