Search code examples
androidandroid-search

How can i send text entered in a search view to a function as a string after the search button is clicked?


Here is an XML file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.thinkx.thinkx.friends"
android:background="#84cae6">
<SearchView
    android:id="@+id/search"
    android:queryHint="  Search ...."
    android:background="@drawable/rounded_edittext"
    android:layout_width="match_parent"
    android:layout_height="40dp">
</SearchView>
<ProgressBar
    android:id="@+id/progressBar2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:visibility="gone"/>
<android.support.v7.widget.RecyclerView
    android:layout_marginTop="50dp"
    android:id="@+id/recyclerView2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="60dp"/>
</android.support.constraint.ConstraintLayout>

And now i want to display the text in this recycler view by replacing the progressbar. I have already seen the android documentation on searchview and also searcched a lot of questions but it didn't work for me!!


Solution

  • Add this to your code:

    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    // Do something when Search icon is clicked on Keyboard, will occur only when Search Icon is pressed
                    return false;
                }
    
                @Override
                public boolean onQueryTextChange(String newText) {
    
                    // do something on text change, it will occur on a single change
                        return false;
                }
            });