Android SearchView to Filter Listview items
Android SearchView Video Tutorial
Almost every application requires search functionality in their app to quickly search for particular content or information.
In this video, we will learn how to add SearchView to our android application. We will see how to filter ListView items using SearchView.
Activity_main.xml
So first we will design our layout and then we move to the implementation part. Let’s get started with a new project.
I have used a Linear layout in our XML file and we require SearchView to search content in our application. Also, I have used ListView which contains items so that we can filter particular items with the help of SearchView.
Below I have provided the full source code of our Activity_main.xml file:
MainActivity.java
Now we will move to our implementation part, so we will declare SearchView and ListView in our main activity.
SearchView searchView; ListView listView;
Thereafter, we will add different items in our ListView that we created. So to add items we use List to store all these items and we require an Adapter to show the list items in our ListView.
ArrayList list; ArrayAdapter adapter;
With the help of ArrayList, we will add items to our list, Let’s say I want to add all months, but you can use anything as per your requirement.
list.add("January"); list.add("February"); list.add("March"); list.add("April"); list.add("May"); list.add("June"); list.add("July"); list.add("August"); list.add("September"); list.add("October"); list.add("November"); list.add("December");
Now we will use Adapter to bind all these items and show in our ListView with the help of setAdapter() method.
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list); listView.setAdapter(adapter);
We are now done with our List part, we will now implement SearchView which is our main focus of this tutorial.
Here we will use a listener for SearchView that is, setOnQueryTextListener() – this sets a listener for user inputs inside SearchView. Same as when we click on a button or typing some text.
We have two methods inside OnQueryTextListener() that is:
- onQueryTextSubmit(String s) – This performs an action when you type the entire text
- onQueryTextChange(String s) – This will listen each character you type in your SearchView
So we will use it here onQueryTextChange(String s). Inside this method we use getFilter().filter(s) method to set data from SearchView to our ListView.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() < @Override public boolean onQueryTextSubmit(String s) < return false; >@Override public boolean onQueryTextChange(String s) < adapter.getFilter().filter(s); return false; >>);
Finally, we are now ready to run our application to see the final result. For a complete video tutorial, you can check my YouTube channel. I have provided the full source code below so that you can try and practice in your android studio.
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity < SearchView searchView; ListView listView; ArrayListlist; ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchView = findViewById(R.id.searchView); listView = findViewById(R.id.listView); list = new ArrayList(); list.add("January"); list.add("February"); list.add("March"); list.add("April"); list.add("May"); list.add("June"); list.add("July"); list.add("August"); list.add("September"); list.add("October"); list.add("November"); list.add("December"); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); listView.setAdapter(adapter); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() < @Override public boolean onQueryTextSubmit(String s) < return false; >@Override public boolean onQueryTextChange(String s) < adapter.getFilter().filter(s); return false; >>); > >
Environment
I have used the below platform to RUN this application however, you can also use windows, the old android studio version.
- Android Studio Version 4.1.1
- Emulator: Android Studio’s emulator
- Operating System: ubuntu 16.04 LTS | 64-bit
So that is all guys for this tutorial, I hope you find this helpful. Let me know in the comment section if you have any questions regarding this example or if you can visit or contact us for any suggestions, I will try to answer as per my knowledge.
Android. Живой поиск с использованием ListView
Простой пример реализации живого поиска за несколько шагов в Android с использованием списка ListView.
1 Шаг. Открываем Android Studio, создаем новый проект с Empty Activity.
2 Шаг. Открываем файл activity_main.xml (путь: res/layout/activity_main.xml) и вставляем в него следующий код:
3 Шаг. Создадим файл list_item.xml (путь: res/layout/list_item.xml) и вставляем в него код отображения элемента в ListView:
4 Шаг. Открываем MainActivity.java и вставляем в него следующий код (оставьте только свой package . ; все остальное заменяйте):
import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends ActionBarActivity < String[] items; ArrayListlistItems; ArrayAdapter adapter; ListView listView; EditText editText; protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView)findViewById(R.id.listview); editText=(EditText)findViewById(R.id.txtsearch); initList(); editText.addTextChangedListener(new TextWatcher() < @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) < >@Override public void onTextChanged(CharSequence s, int start, int before, int count) < if(s.toString().equals(""))< // reset listview initList(); >else < // perform search searchItem(s.toString()); >> @Override public void afterTextChanged(Editable s) < >>); > public void searchItem(String textToSearch) < for(String item:items)< if(!item.contains(textToSearch))< listItems.remove(item); >> adapter.notifyDataSetChanged(); > public void initList()< items=new String[]; listItems=new ArrayList<>(Arrays.asList(items)); adapter=new ArrayAdapter(this, R.layout.list_item, R.id.txtitem, listItems); listView.setAdapter(adapter); > >
Все, запускаем приложение в эмуляторе или на устройстве. В итоге мы получим следующее:
Если у вас есть вопросы или предложения по улучшению кода описанного в статье пишите в комментариях.
Я всегда открыт к конструктивному диалогу
Рекомендуемые
Комментарии
public void searchItem(String textToSearch)
for(String item:items)
if(!item.contains(textToSearch))
listItems.remove(item);
>
> adapter.notifyDataSetChanged(); >
public void searchItem(String textToSearch)
for(String item:items)
String textToSearch1 = textToSearch.toLowerCase();
if(!item.toLowerCase().contains(textToSearch1))
listItems.remove(item);
>
>
adapter.notifyDataSetChanged();
>
А как изменить код, чтобы в поиске можно было искать части фраз, а не по одному слову?
Если в поиск ввести слово а затем нажать пробел то он искать не будет
Скажите пожалуйста, как сделать что бы ListView был кликабельным и открывал Активити? И после поиска открывались нужные Активити?
public class MainActivity extends AppCompatActivity
String[] items;
ArrayList listItems;
ArrayAdapter adapter;
ListView listView;
EditText editText;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.listview);
editText=(EditText)findViewById(R.id.txtsearch);
initList();
editText.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
>
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
if(s.toString().equals(""))
// reset listview
initList();
> else
// perform search
searchItem(s.toString());
>
>
@Override
public void afterTextChanged(Editable s)
>
>);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
public void onItemClick(AdapterView >parent, View view, int position, long id)
switch (position)
case 0:
intent = new Intent(MainActivity.this, SecondActivity.class); //Заполняем Intent
break;
case 1:
intent = new Intent(MainActivity.this, ThirdActivity.class); //Заполняем Intent
break;
>
startActivity(intent); //Запускаем активность
>
>);
>
public void searchItem(String textToSearch)
for(String item:items)
String textToSearch1 = textToSearch.toLowerCase();
if(!item.toLowerCase().contains(textToSearch1))
listItems.remove(item);
>
>
adapter.notifyDataSetChanged();
>
public void initList()
items=new String[];
listItems=new ArrayList<>(Arrays.asList(items));
adapter=new ArrayAdapter(this, R.layout.list_item, R.id.txtitem, listItems);
listView.setAdapter(adapter);
>
>
Столкнулся с такой проблемой как при вводе текста с русским регистром(Listview тоже заполняя на русском, поиск производится с русского языка) дает ошибку. Можете сказать что делать?
How to Search an Item in ListView using EditText and TextWatcher in Android?
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.