How to Implement Android SearchView with Example


The Android SearchView widget is a versatile tool that enables effortless information search within an app, boosting user experience and efficient data retrieval. Its intuitive and user-friendly interface simplifies content discovery, allowing users to input their queries and receive quick results. With the integration of SearchView, overall app usability improves significantly.

The power of SearchView's search capabilities can be harnessed to smoothly integrate potent search functionality into any Android app. This article provides a practical example that explores how to implement SearchView seamlessly into your own application. Once implemented, your users will be able to locate the desired information quickly and efficiently.

SearchView

The Java SearchView is an Android framework widget that empowers application users to perform search operations with ease. It presents a structured user interface to input and submit search queries within the app.

To utilize the SearchView component, one would typically set up a listener function to capture search query events and manage the related functionality. Achieving this involves creating custom methods to handle alterations in query text, query submission, and query clearing.

SearchView searchView = findViewById(R.id.searchView);

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        // Handle the search query submission
        performSearch(query);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        // Handle changes in the search query text
        updateSearchResults(newText);
        return true;
    }
});

Approaches

To implement Android SearchView, there are multiple methods you can follow. Here are a few approaches you can take:

  • Using the onCreateOptionsMenu() Method

  • Extending AppCompatActivity and Implementing SearchView.OnQueryTextListener

  • Implementing SearchView in a Fragment

Using the onCreateOptionsMenu() Method

In this method, you inflate the menu XML file in onCreateOptionsMenu() and retrieve the SearchView widget from the menu item. By setting up listeners for search queries and events, you can handle user input and implement the necessary logic to perform searches and display results.

Algorithm

  • Inflate the menu XML file in onCreateOptionsMenu().

  • Retrieve the SearchView widget from the menu item.

  • Set up listeners for search queries and events.

  • Handle user input and implement logic to perform searches and display results.

Example

public class MainActivity extends AppCompatActivity {
   private SearchView searchView;

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.menu_main, menu);
      MenuItem searchItem = menu.findItem(R.id.action_search);
      searchView = (SearchView) searchItem.getActionView();

      // Set up search listeners
      searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
         @Override
         public boolean onQueryTextSubmit(String query) {
            // Perform search operation based on the query
            performSearch(query);
            return true;
         }

         @Override
         public boolean onQueryTextChange(String newText) {
            // Update search results as the user types
            updateSearchResults(newText);
            return true;
         }
      });

      return true;
   }

   private void performSearch(String query) {
      // Dummy search operation
      List<String> searchResults = new ArrayList<>();
      searchResults.add("Dummy Result 1");
      searchResults.add("Dummy Result 2");

      // Display search results
      displayResults(searchResults);
   }

   private void updateSearchResults(String newText) {
      // Dummy logic to update search results dynamically
      // based on the user's input
   }

   private void displayResults(List<String> results) {
      // Dummy logic to display the search results
      for (String result : results) {
         Log.d("Search Result", result);
      }
   }
}

Output

Extending AppCompatActivity and Implementing SearchView.OnQueryTextListener

By extending AppCompatActivity in your activity class, you can override onCreateOptionsMenu() to inflate the menu XML file. Retrieve the SearchView widget from the menu item and implement SearchView.OnQueryTextListener. Override its methods to handle search queries and events, allowing you to execute search operations and display the relevant results.

Algorithm

  • Extend AppCompatActivity in the activity class.

  • Override onCreateOptionsMenu() and inflate the menu XML file.

  • Retrieve the SearchView widget from the menu item.

  • Implement SearchView.OnQueryTextListener.

  • Override its methods (onQueryTextSubmit() and onQueryTextChange()) to handle search queries and events.

  • Execute search operations and display relevant results based on user input.

Example

public class MainActivity extends AppCompatActivity implements SearchView.
OnQueryTextListener {
   private SearchView searchView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      // Other initialization code

      // Set up search view
      searchView = findViewById(R.id.search_view);
      searchView.setOnQueryTextListener(this);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }

   @Override
   public boolean onQueryTextSubmit(String query) {
      // Perform search operation based on the query
      performSearch(query);
      return true;
   }

   @Override
   public boolean onQueryTextChange(String newText) {
      // Update search results as the user types
      updateSearchResults(newText);
      return true;
   }

   private void performSearch(String query) {
      // Dummy search operation
      List<String> searchResults = new ArrayList<>();
      searchResults.add("Dummy Result 1");
      searchResults.add("Dummy Result 2");

      // Display search results
      displayResults(searchResults);
   }

   private void updateSearchResults(String newText) {
      // Dummy logic to update search results dynamically
      // based on the user's input
   }

   private void displayResults(List<String> results) {
      // Dummy logic to display the search results
      for (String result : results) {
         Log.d("Search Result", result);
      }
   }
}

Output

Implementing SearchView in a Fragment

When using fragments, you inflate the menu XML file in onCreateOptionsMenu() of the Fragment. Retrieve the SearchView widget from the menu item, and within the Fragment, implement SearchView.OnQueryTextListener. By overriding its methods, you can handle search queries and events specific to the Fragment, enabling search functionality and displaying results accordingly.

Algorithm

  • Inflate the menu XML file in onCreateOptionsMenu() of the Fragment.

  • Retrieve the SearchView widget from the menu item.

  • Implement SearchView.OnQueryTextListener in the Fragment.

  • Override its methods (onQueryTextSubmit() and onQueryTextChange()) to handle search queries and events.

  • Perform search operations and display results specific to the Fragment's context.

Example

public class MyFragment extends Fragment implements 
SearchView.OnQueryTextListener {
   private SearchView searchView;

   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater 
inflater) {
      inflater.inflate(R.menu.menu_fragment, menu);
      MenuItem searchItem = menu.findItem(R.id.action_search);
      searchView = (SearchView) searchItem.getActionView();
      searchView.setOnQueryTextListener(this);
   }

   @Override
   public boolean onQueryTextSubmit(String query) {
      // Perform search operation based on the query
      performSearch(query);
      return true;
   }

   @Override
   public boolean onQueryTextChange(String newText) {
      // Update search results as the user types
      updateSearchResults(newText);
      return true;
   }

   private void performSearch(String query) {
      // Dummy search operation
      List<String> searchResults = new ArrayList<>();
      searchResults.add("Dummy Result 1");
      searchResults.add("Dummy Result 2");

      // Display search results
      displayResults(searchResults);
   }

   private void updateSearchResults(String newText) {
      // Dummy logic to update search results dynamically
      // based on the user's input
   }

   private void displayResults(List<String> results) {
      // Dummy logic to display the search results
      for (String result : results) {
         Log.d("Search Result", result);
      }
   }
}

Output

Conclusion

In this tutorial, implementing Android SearchView provides a convenient way for users to search for specific information within an app. By utilizing various methods such as onCreateOptionsMenu(), extending AppCompatActivity, and implementing SearchView.OnQueryTextListener, developers can incorporate search functionality and enhance the user experience.

Whether it's a simple search feature or a more complex implementation with dynamic results, SearchView empowers developers to create intuitive search interfaces that improve app usability and make it easier for users to find the desired content.

Updated on: 27-Jul-2023

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements