Jameskittu
Jameskittu

Reputation: 598

search text from a text file in android

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

Upvotes: 1

Views: 3715

Answers (2)

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

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){

            }

    }

Upvotes: 3

iDroid
iDroid

Reputation: 10533

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.

Upvotes: 0

Related Questions