Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods of SearchView
3.
Example of SearchView
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Android SearchView

Author Rahul Sain
2 upvotes
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Android SearchView is a user interface for search queries supplied through a search provider. The SearchView widget can be placed on a ToolBar/ActionBar or within a layout.

In this article, we will learn about SearchView in Android. But before jumping into this, we would strongly recommend learning about VideoView.

The upcoming section will discuss various methods provided by SearchView for searching and displaying the searched data with the help of some examples.

Methods of SearchView

SearchView is collapsible by default and can be iconified using the setIconifiedByDefault(true) function of the SearchView class. SearchView employs the setIconifiedByDefault(false) method to make the search field visible.

Let's look at some methods provided by the SearchView for searching data and fetching it.

  1. getQuery(): This function retrieves the query string in the text field of a search view. This method returns a CharSequence type value.
  2. getQueryHint()This function returns the hint text that will appear in the query text box. This method returns a value of the CharSequence type.
  3. isIconfiedByDefault()This function retrieves the search field's default iconified state. This method returns either false or true as a Boolean result.
  4. setIconifiedByDefault(Boolean iconify)This function is used to set the search field's default or resting state. We set the Boolean value true or false in this procedure.
    When a SearchView is used as an action view for a collapsible menu item in an Action Bar, it must be set to iconified by default using the setIconfiedByDefault(true) function. If you want the search field to be visible at all times, use setIconifiedByDefault (false). This function's default value is true. You can also set iconified from XML to true or false by setting the iconfiedByDefault parameter to true or false.
  5. setQueryHint(CharSequence hint)This function is used to specify the hint text that should appear in the query text box. This method accepts values of the CharSequence type.
  6. setOnQueryTextListener(OnQueryTextListenerlistener): It is a search activity performed by the user within the SearchView.
  7. setOnQueryTextFocusChangeListener(OnFocusChangeListenerlistener): When the focus of the query text box changes, this listener notifies you.
  8. onQueryTextSubmit(String query): It searches the query on the content submission using SearchView editor. It is case-sensitive.
  9. onQueryTextChange(String newText): It searches the query when updating the text in the SearchView editor.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of SearchView

In the SearchView sample below, we show SearchView and ListView. In this example, we establish a language name list and then use the adapter to populate the data in the ListView. Finally, we use SearchView.OnQueryTextListener to filter the language list by the search query.

The changed main activity file MainActivity.kt is shown below.

Code:

package com.codingninjas.ui

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity(), SearchView.OnQueryTextListener {
    private lateinit var listView: ListView
    private lateinit var adapterLanguage: LanguageListViewAdapter
    private lateinit var searchView: SearchView
    private lateinit var languageNameList: Array<String>
    private var arraylist: ArrayList<Languages> = ArrayList()
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        languageNameList = arrayOf(
            "English", "Hindi", "Telegu",
            "Gujrati", "Punjabi", "Haryanavi", "Russian", "Pakistani",
            "Chinese", "American", "African", "British"
        )

        listView = findViewById<View>(R.id.lV) as ListView
        for (i in languageNameList.indices) {
            val languages = Languages(languageNameList[i])
            // Binds all strings into an array
            arraylist.add(languages)
        }

        adapterLanguage = LanguageListViewAdapter(this, arraylist)

        listView.adapter = adapterLanguage

        searchView = findViewById<View>(R.id.sV) as SearchView
        searchView.setOnQueryTextListener(this)
    }

    override fun onQueryTextSubmit(query: String): Boolean {
        Toast.makeText(this, query, Toast.LENGTH_SHORT).show()
        return false
    }

    override fun onQueryTextChange(newText: String): Boolean {
        adapterLanguage.filter(newText)
        return false
    }
}

In this stage, we open MainActivity and add code to launch SearchView and ListView. In this case, we establish a Langauge name list and then use the adapter to populate the data in the ListView. We also use SearchView.OnQueryTextListener to filter the language list based on the search term.

Our main_activity.xml looks like the code snippet given below.

Code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
 xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="SearchView"
        android:textSize="35sp" />

    <SearchView
        android:id="@+id/sV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:background="@color/teal_200"
        android:queryHint="Search Here"
        android:layout_margin="8dp"
        android:iconifiedByDefault="false"/>

    <ListView
        android:id="@+id/lV"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/sV" />

</RelativeLayout>

In this step, we will open an XML file and add code to display a SearchView and a ListView using their various characteristics.

We will now bind our data to LanguageListViewAdapter.kt adapter while using the code shown below.

Code:

package com.codingninjas.ui

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import java.util.*


class LanguageListViewAdapter(
    mContext: Context, private var languagesList: MutableList<Languages>
) :
    BaseAdapter() {
    private var inflater: LayoutInflater = LayoutInflater.from(mContext)
    private val arraylist: ArrayList<Languages> = ArrayList<Languages>()

    inner class ViewHolder {
        var name: TextView? = null
    }

    override fun getCount(): Int {
        return languagesList.size
    }

    override fun getItem(position: Int): Languages {
        return languagesList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, view: View?, parent: ViewGroup): View? {
        var view1 = view
        val holder: ViewHolder
        if (view1 == null) {
            holder = ViewHolder()
            view1 = inflater.inflate(R.layout.list_view_adapter_item, null)
            holder.name = view1.findViewById<View>(R.id.name) as TextView
            view1.tag = holder
        } else {
            holder = view1.tag as ViewHolder
        }
        holder.name?.text = languagesList[position].name
        return view1
    }

    fun filter(charText: String) {
        var charText1 = charText
        charText1 = charText1.lowercase(Locale.getDefault())
        languagesList.clear()
        if (charText1.isEmpty()) {
            languagesList.addAll(arraylist)
        } else {
            for (wp in arraylist) {
                if (wp.name.lowercase(Locale.getDefault()).contains(charText1)) {
                    languagesList.add(wp)
                }
            }
        }
        notifyDataSetChanged()
    }

    init {
        arraylist.addAll(languagesList)
    }
}

In this case, we extend BaseAdapter in the LanguageListViewAdapter.kt class and then use the Model class Languages.kt to set the data in the ListView.

Our Model Class Languages.kt have the following property.

Code:

package com.codingninjas.ui

class Languages(s: String) {
    var name: String = s
}

A constructor is used to set the animal name, and a function is used to retrieve the animal name.

And finally, we will use our list_view_adapter_item.xml for designing each item UI.

Code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView
        android:id="@+id/nameType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/nameType" />

</RelativeLayout>

Here, we're making the view of an item presented within each row.

Output:

When you launch the app, you will see a list of different languages' names. In SearchView, type the first language character that comes to mind, and the results will be sorted.

And when you click on search, you will see a Toast message which will display the query you sent to SearchView.

Check this out : usb debugging

FAQs

  1. What is a toolbar Android?
    Ans: Toolbar is a type of ViewGroup in Android applications that may be placed in an activity's XML layouts. Google's Android team first launched it with the release of Android Lollipop (API 21). The Toolbar is essentially the ActionBar's upgraded successor.
     
  2. What is the elevation in Android?
    Ans: Elevation is the distance or relative depth between two surfaces along the z-axis. The elevation is commonly recorded in density-independent pixels in the same units as the x and y axes (DP).
     
  3. How can you provide custom search suggestions while utilizing the Android search dialog or search widget?
    Ans: You can provide custom search suggestions produced from data in your application when utilizing the Android search dialog or search widget. For example, if your application is a word dictionary, you can suggest terms from the dictionary that fit the text input thus far.

Key Takeaways

In this article, we have extensively discussed SearchView in Android and its essential methods.

You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.

We hope that this blog has helped you enhance your knowledge regarding SearchView and if you would like to learn more, check out our articles Video View. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass