Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Higlight Particular Word in Text View

I am creating one application in which I am searching for a Perticular word in text view.I have one edit text,one text view and one button,when I am entering any word in edit text and clicking on button it gives me the line position and position of word in that line from entire text file...I have append text file's contain in text view...now my question is can I highlight that all word which is there in text view entered by edit text.?if I can than please tell me how to do it..if any one have idea of it?

like image 392
Aamirkhan Avatar asked Dec 15 '11 10:12

Aamirkhan


2 Answers

You can also do it by using a Spannable, which is convenient as you know the position of the word:

    SpannableString res = new SpannableString(entireString);
    res.setSpan(new ForegroundColorSpan(color), start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

Where entireString is the string in which the word to highlight exists, color is the color you want the hightlighted text to have, start is the position of the word and end is where the word ends (start+word.length()).

The SpannableString res can then be applied to your textview like a regular string:

textView.setText(res);

Note: If you want the background of the text to get a color rather than the text itself, use a BackgroundColorSpan instead of a ForegroundColorSpan.

Edit: In your case it would be something like this (you will have to save the value of linecount and indexfound for when you read the entire text):

for(String test="", int currentLine=0; test!=null; test=br2.readLine(), currentLine++){
    if(currentLine==linecount){
        SpannableString res = new SpannableString(test);
        res.setSpan(new ForegroundColorSpan(0xFFFF0000), indexfound, indexfound+textword.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    tv.append("\n"+"    "+test);
}
like image 91
Jave Avatar answered Nov 09 '22 03:11

Jave


Yes You can highlight some portion of the text view by writing HTML

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
like image 32
san Avatar answered Nov 09 '22 04:11

san