1

I kept the text file inside the asset folder & I'm able to display the whole text in a TextView in my activity. But now I need to add search function inside my activity with highlighting the searched text. Can anyone pls suggest any idea or send me code snippet to finish this.

Thanks in Advance

Krishnakumar P

Jameskittu
  • 598
  • 2
  • 8
  • 17

2 Answers2

3

Use the folowing code to get highlight the text.

    void hightLightText(TextView textView, String searchString){
        try{
//if mydata.txt file is present in assets directory 
            InputStream fin = getAssets().open("mydata.txt");
            byte[] buffer = new byte[fin.available()];
            fin.read(buffer);
            String actualdata = new String(buffer);
            String withHighLightedText = actualdata.replaceAll(searchString, "<font color='red'>"+actualdata)+"</font>";
            String styledText = "This is <font color='red'>simple</font>.";
            textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
            }catch(Exception ex){

            }

    }
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
  • 1
    Nice elegant solution, thanks Sunil. There's a small typo in there, think it should be like this: String withHighLightedText = actualdata.replaceAll(searchString, ""+searchString+"");You just saved me a lot of messing about, very much appreciated! – BasicPleasureModel Feb 28 '13 at 14:04
0

I assume you temporarily save your text somewhere (e. g. String, StringBuilder) before displaying it in the TextView. So you can grab the search string and look if your temporarily saved text contains it (e. g. String.contains()), in positive case you can highlight the text of your TextView. Here is an example how to highlight.

Community
  • 1
  • 1
iDroid
  • 10,403
  • 1
  • 19
  • 27