Search code examples
androidandroid-edittextandroid-search

Implementing Search Functionality on Text Change in Android


I am trying to Implement the Search Functionality in my Android Application using the link http://developer.android.com/guide/topics/search/search-dialog.html.

It can only search the text entered when pressed on the search button. But it cannot perform search when the text in the search bar changes. I want to implement that kind of functionality, just as it is in the "People" or "Contact" App in the Android phones.

I have tried to search for this a lot but unable to find any links. If anyone can direct my to those links, it would be useful. Thanks in advance.

Edit:

I have implemented the search functionality in the MainActivity Only. The code for MainActivity.java:

findViewById(R.id.id1).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onSearchRequested();
    }
});

Android Manifest:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.SEARCH" />
        <action android:name="android.intent.action.VIEW" />
    </intent-filter>
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/activity_search" />
</activity>

Solution

  • Just do this if you are Using Search bar,

    lv.setTextFilterEnabled(true);
    

    But I recommend you to use EditText instead of Search bar, if you agree do this for EditText

    edittext = (EditText) findViewById(R.id.edittext);
    edittext.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                Search_Activity.this.adapter.getFilter().filter(s);
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
    
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        });
    

    I hope this will help you.