How to Search an Item in ListView using EditText and TextWatcher in Android?
Last Updated :
09 Dec, 2021
Some applications provide a search bar for looking up any particular item from a list of items. Technically, a search bar is an EditText and an item list can be a ListView, RecyclerView, or a GridView that contains some items. Now, when a user types something in the EditText, the list must update in accordance with the text that the user types. String matching algorithms are used to check if the typed text is a substring of any of the list items, and if any, then those items are displayed in the updates ListView. However, creating a separate function or an algorithm to perform this search operation consumes more lines on the editor. To this, one can make use of a TextWatcher object, a public interface, which implements on the EditText and checks if the text changes. So in this article, we will show you how you could implement a TextWatcher on an EditText to update the resultant ListView when input is given by the user. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Create an EditText on the top of the activity which shall be the assumed search bar and a ListView below it for displaying the items.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="50sp"
android:inputType="text"/>
<ListView
android:id="@+id/list_view"
android:layout_below="@id/edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. We declared an array of items as shown in the code. These items are initially displayed in the ListView with the use of an adapter. Next, the TextWatcher is implemented on the EditText. TextWatcher implements three member functions, i.e., beforeTextChanger(), onTextChanged(), and afterTextChanged(). We are concerned with onTextChanged() as we want to update the ListView when the text changes in real-time. This function takes in the entire string from the EditText, filters the adapter for array elements based on the input and the updated ListView is displayed. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declare and Initialize the EditText
// and ListView from the layout file.
val mSearch = findViewById<EditText>(R.id.edit_text)
val mListView = findViewById<ListView>(R.id.list_view)
// Declare array of elements, create an adapter
// and display the array in the ListView
val mCities = arrayOf("Mumbai", "Mohali", "Delhi", "Dehradun", "Darjeeling", "Bengaluru")
val mArrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, mCities)
mListView.adapter = mArrayAdapter
// TextWatcher to check if the EditText text changes
mSearch.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// Do Nothing
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
mArrayAdapter.filter.filter(s)
}
override fun afterTextChanged(s: Editable?) {
// Do Nothing
}
})
}
}
Output:
We can see that the ListView is updated based on the input given.
Similar Reads
How to Detect Scroll Up and Down Gestures in a ListView in Android? A ListView in Android is a scrollable list used to display items. Data, which is a list or array of items fetched from a source or hardcoded in the application can be displayed row-wise using a ListView. If the items are less, then the list may not even reach the bottom of the screen. However, if th
4 min read
How to Make TextView and EditText Selectable in Android? In this article, we are going to implement a very important feature related to TextView. While using any social media app or like using Facebook you may have seen there is a particular type of TextView which you cannot copy like a caption that people write on their posts. You can select the message
3 min read
How to Set Minimum and Maximum Input Value in EditText in Android? In Android, EditText is a subclass of TextView which is configured to be editable. EditText is used for giving textual input such as characters, strings, numbers, etc. It has no limitation on the type of input unless explicitly attributed. Meaning we can attribute the EditText to accept only a strin
3 min read
How to Remove ListView Item Divider in Android? ListView in Android is generally used for displaying or listing items in the form of a list. Each item in the list is clickable and the list itself is vertically scrollable. In general, each item is separated by a thin line or a horizontal stroke. This line is termed an item divider in Android as it
3 min read
How to Add Mask to an EditText in Android? EditText is an android widget. It is a User Interface element used for entering and modifying data. It returns data in String format. Masking refers to the process of putting something in place of something else. Therefore by Masking an EditText, the blank space is replaced with some default text, k
3 min read
Add an Input Filter to the TextField in Android using Jetpack Compose In Jetpack Compose, a TextField is a UI element that lets users type in text as an input. This input can then be stored and used for various desired functions. As TextField has no character restrictions, users can type in any character. However, there can be a system where the application would acce
3 min read
How to Detect Long Press on ListView Items in Android? ListView in Android is a ViewGroup that is used to display items in rows and has an adapter that inserts the desired elements into the list. Once the items are inserted into the ListView, they can be clicked and the desired action can be performed. As multiple operations can be performed on a ListVi
3 min read
How to Add Footer to ListView in Android with Kotlin? In Android, a ListView is a view used to display a list of items separated by a stroke. A ListView adapter is used to supply items from the main code to the ListView in real-time. A Footer is anything that gets added at the bottom of any element. So, a Footer in ListView is a layout that is present
3 min read
How to Add SearchView in Google Maps in Android? We have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name a
4 min read
How to Change the ListView Text Color in Android? In Android, a ListView is a UI element used to display the list of items. This list is vertically scrollable and each item in the ListView is operable. A ListView adapter is used to supply items from the main code to the ListView in real-time. By default, the TextView font size is 14 sp and color is
3 min read