SearchView in Kotlin XML: Implement Android Search Functionality

Implementing a robust and user-friendly search functionality is a crucial aspect of modern Android application development. The SearchView widget, available in the Android SDK, offers a powerful way to provide search capabilities within your app. In this comprehensive guide, we’ll explore how to implement search functionality using the SearchView widget in Kotlin XML development for Android.

What is the SearchView Widget?

The SearchView widget is an Android UI component that allows users to enter search queries. It typically appears as an expandable search box that can be integrated into the app’s Toolbar or as a standalone component within a layout. The SearchView provides features like query suggestions, voice search, and customizable behaviors.

Why Use SearchView?

  • Enhanced User Experience: Provides a familiar and intuitive interface for searching within the app.
  • Versatility: Can be customized and integrated into various parts of the UI, such as the Toolbar or a dedicated search screen.
  • Advanced Features: Supports query suggestions, voice search, and more, enhancing the overall search experience.

How to Implement Search Functionality with SearchView in Kotlin XML

Follow these steps to implement search functionality using the SearchView widget in your Android application.

Step 1: Add SearchView to XML Layout

First, add the SearchView widget to your XML layout file. You can integrate it into your Toolbar or include it as a standalone element.

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<androidx.appcompat.widget.SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:iconifiedByDefault="false"
    android:queryHint="Search..." />

Here, the SearchView is configured to occupy the full width and displays a hint text, ‘Search…’. The iconifiedByDefault attribute is set to false to ensure the search box is always expanded.

Step 2: Initialize SearchView in Activity

In your Activity or Fragment, retrieve the SearchView widget using its ID and set up a listener to handle search queries.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar

class MainActivity : AppCompatActivity() {

    private lateinit var searchView: SearchView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        searchView = findViewById(R.id.searchView)
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                // Handle search query submission
                if (!query.isNullOrEmpty()) {
                    performSearch(query)
                    return true
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                // Handle search query text change
                if (!newText.isNullOrEmpty()) {
                    updateSearchSuggestions(newText)
                    return true
                }
                return false
            }
        })
    }

    private fun performSearch(query: String) {
        // Implement your search logic here
        Toast.makeText(this, "Searching for: $query", Toast.LENGTH_SHORT).show()
    }

    private fun updateSearchSuggestions(newText: String) {
        // Update search suggestions based on newText
        // This can involve querying a database or API for suggestions
        Toast.makeText(this, "Updating suggestions for: $newText", Toast.LENGTH_SHORT).show()
    }
}

In this code:

  • The SearchView is retrieved using findViewById(R.id.searchView).
  • setOnQueryTextListener is used to listen for query submission and text change events.
  • The onQueryTextSubmit method is called when the user submits a search query.
  • The onQueryTextChange method is called whenever the text in the SearchView changes.

Step 3: Implement Search Logic

Implement the performSearch function to execute your search logic. This can involve querying a local database, making an API call, or filtering data from a list.


private fun performSearch(query: String) {
    // Example: Searching through a list of items
    val items = listOf("Apple", "Banana", "Cherry", "Date", "Fig")
    val results = items.filter { it.contains(query, ignoreCase = true) }

    if (results.isNotEmpty()) {
        Toast.makeText(this, "Results: ${results.joinToString()}", Toast.LENGTH_SHORT).show()
    } else {
        Toast.makeText(this, "No results found for: $query", Toast.LENGTH_SHORT).show()
    }
}

This example demonstrates a simple search through a predefined list of items, displaying the results in a Toast message.

Step 4: Implement Search Suggestions

Implement the updateSearchSuggestions function to provide users with real-time search suggestions as they type. This often involves querying a data source for matching suggestions.


private fun updateSearchSuggestions(newText: String) {
    // Example: Providing search suggestions from a list
    val suggestions = listOf("Apple", "Banana", "Cherry", "Date", "Fig")
    val filteredSuggestions = suggestions.filter { it.startsWith(newText, ignoreCase = true) }

    if (filteredSuggestions.isNotEmpty()) {
        Toast.makeText(this, "Suggestions: ${filteredSuggestions.joinToString()}", Toast.LENGTH_SHORT).show()
        // You would typically display these suggestions in a dropdown or list view
    } else {
        Toast.makeText(this, "No suggestions found for: $newText", Toast.LENGTH_SHORT).show()
    }
}

This example showcases how to filter suggestions based on the user’s input and display them using a Toast. In a real-world application, you would replace the Toast with a proper UI element like a ListView or RecyclerView.

Step 5: Add Voice Search Functionality (Optional)

The SearchView widget can also be integrated with voice search. Here’s how to add voice search functionality:


import android.content.Intent
import android.speech.RecognizerIntent
import androidx.activity.result.contract.ActivityResultContracts

// Add this inside your Activity class
private val voiceSearchResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == RESULT_OK) {
        val matches: List? = result.data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
        if (!matches.isNullOrEmpty()) {
            val searchQuery = matches[0]
            searchView.setQuery(searchQuery, true) // Submits the query
        }
    }
}

private fun startVoiceSearch() {
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
        putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to search")
    }

    try {
        voiceSearchResult.launch(intent)
    } catch (e: Exception) {
        Toast.makeText(this, "Voice search not available on this device", Toast.LENGTH_SHORT).show()
    }
}

Then, add this inside your onCreate method after initializing your SearchView:


searchView.setOnSearchClickListener {
    startVoiceSearch()
}

In this example:

  • A voiceSearchResult ActivityResultLauncher is used to handle the result from the voice recognition intent.
  • The startVoiceSearch function initiates the voice recognition intent and processes the result.
  • Clicking the search icon in the SearchView will now activate voice search.

Advanced Customizations

The SearchView widget offers various customization options to fit your app’s design and functionality.

  • Changing the Query Hint: Customize the hint text displayed in the search box.
  • Setting Input Type: Define the type of input (e.g., text, number) accepted by the search box.
  • Adding Search Icons: Use custom icons to match your app’s theme.
  • Implementing Full-Screen Search: Transition to a full-screen search activity for a more immersive experience.

Conclusion

The SearchView widget is a powerful tool for implementing search functionality in your Android applications. By following the steps outlined in this guide, you can create a user-friendly and efficient search interface using Kotlin and XML. Properly implemented search enhances the usability of your app, providing users with quick access to the information they need.