- Implementing Search View in Android
- A). Introduction
- B). Objectives
- C). Prerequisites
- D). Getting started
- i). Project structure
- ii). Setting up plugins
- E). Creating the User Interface
- F). Creating the data model
- G). Setting up RecyclerView adapter
- H). How the linear search algorithm works
- I). Implementing search algorithm
- i). Just before the onCreate function
- ii). Inside the onCreate function
- iii). Initialization stage
- iv). Understanding the logic behind performSearch function
- v). updateRecyclerView() explained
- Conclusion
- About the author
- Want to learn more about the EngEd Program?
- Русские Блоги
- Использование SearchView в Android
- Очки знаний в этой статье
- 1. Введение в SearchView
- 2. Функция поиска NetEase Cloud Music
- 2.1 Базовая реализация функции поиска
- 2.1.1 Инициализация и мониторинг кнопки поиска
- 2.2 Украшение интерфейса
- 2.2.1 Текст приглашения по умолчанию
- 2.2.2 Кнопка поиска не исчезает
- 2.2.3 Кнопка поиска, чтобы отменить проблему закрытия значка
- 2.2.4 Расширение панели поиска по умолчанию
- 2.2.5 Изменить значок поиска или удалить значок
- 2.2.6 Изменить цвет текста
Implementing Search View in Android
April 6, 2021
When dealing with a vast amount of data, it can sometimes be strenuous to find the piece of data that you want. This problem can be solved by filtering out the necessary data with respect to the keyword(s) provided. This is where a SearchView comes in.
A). Introduction
A SearchView is an Android widget that simplifies the process of manoeuvering through a bunch of data trying to find a match. This improves the users’ experience by saving time.
B). Objectives
In this tutorial, we will learn how to use a RecyclerView to implement SearchView in Android. The sample data used in this project will be generated explicitly for demo purposes.
C). Prerequisites
To follow through this tutorial, you’ll need to:
D). Getting started
First, fire up Android Studio and create an Empty Activity project. If you are familiar with creating projects and setting up a RecyclerView, you can jump to step (H) .
i). Project structure
When the build process is done, expand the package under app/java/»package-name» and create three packages named, adapter , model , and view respectively.
They should look like this.
This aids in organizing the project such that related files belong to the same category. This way robust, production-quality apps can be built rapidly. You can learn more about application architecture here.
With that said, drag and drop the MainActivity.kt file into the view package.
ii). Setting up plugins
Since we’re going to use dataBinding, open build.gradle(Module) file and add the following plugin inside the plugins scope.
This plugin comes with utilities responsible for dataBinding and needs to be enabled so that it can be used. Add the following inside the Android block (in the same file).
Sync the project and wait for the build to finish.
E). Creating the User Interface
We only need two views in the UI, a SearchView and a RecyclerView. Paste the following code into the activity_main.xml file to create them.
Remember to enclose the root viewGroup with tag to generate a binding class for this XML file.
Next, we need to create an item that will be populated in the RecyclerView. Create an xml layout file named row_item.xml and paste the following code in it.
This creates two TextViews that will display a person’s name and age respectively. The actual data will be fetched and bound at runtime.
To preview how this will appear in a RecyclerView at runtime, add the following attribute inside the RecyclerView tag.
F). Creating the data model
A model is an independent component that is responsible for handling the data of an application. In our case, we need to use a list of data that is of the type Person . The Person data class holds two non-nullable variables, name and age.
Go ahead and create a data class inside the model package and paste the following code just below the package name.
G). Setting up RecyclerView adapter
A RecyclerView is a flexible widget that can bind a variety of data with respect to its type. However, there’s no specific type of data that should be provided to it. An adapter helps us prepare the RecyclerView to handle the given data.
Inside the adapter package (created at step D(i)), create a Kotlin class named PersonAdapter . This class will extend a RecyclerView adapter and accept an ArrayList of type Person (the data class created in the previous step).
Unlike a List, an ArrayList supports the addition and deletion of elements at runtime which is why we’re using it.
Copy and paste the code below in the PersonAdapter.kt file:
Press Alt + Enter to fix missing imports. The code above enables the RecyclerView to bind views and populate them with data in the order it appears in the ArrayList. This tutorial elaborates further on how an Adapter works.
H). How the linear search algorithm works
Just like any other task, searching is a process that requires a series of steps to be performed. In this tutorial, we’ll make use of the Linear search algorithm .
First set up two lists, one containing all the data under consideration, and leave the other one empty. We’ll therefore loop through the elements in the first list comparing each content with the given keyword.
In this case, the keyword is the text typed by the user in the SearchView. If a match is found, the element containing the match is cloned into the second list and the RecyclerView is updated with the new list.
When working with a relatively large list or a list of unknown size, it is recommended to update the RecyclerView every time a match is found.
Otherwise, the app might land into an ANR (App Not Responding) situation due to high memory consumption. Also, the newly created list should be cleared when not required for the same reason.
I). Implementing search algorithm
Moving on, open the MainActivity.kt file and paste the following code sequentially as shown.
i). Just before the onCreate function
This declares private global variables that we’ll use later. The people and matchedPeople ArrayLists will hold all data and matched data respectively as explained in step (H) .
ii). Inside the onCreate function
This is where we bind the UI and the logic of the App.
iii). Initialization stage
Here, we need to initialize the RecyclerView and prepare the SearchView. To do so, paste the following code just below onCreate() .
In this function, we have initialized the people list with ten entities of type Person . This list can be as large as desired.
Remember to call the above two functions in the onCreate() method as shown in the snippet below.
iv). Understanding the logic behind performSearch function
Have you been wondering how the SearchView knows when the user has typed something? Well, a searchView has an inbuilt function, setOnQueryTextListener() that accepts an object of type OnQueryTextListener as the argument.
This object is an interface , a member of SearchView class and contains two member functions, onQueryTextSubmit() and onQueryTextChange() .
The two accept a nullable parameter of the type String and must be implemented using the override keyword when using the interface.
As the name suggests, onQueryTextSubmit() is called when the user clicks the submit button of the SearchView. On the other hand, onQueryTextChange() is called every time the text in the SearchView changes.
The change may be due to the addition or deletion of characters. All in all the two functions call another function, search() discussed below.
First, the matchedPeople list is cleared or set to an empty arrayList to avoid accumulation of the previous search. If the argument for parameter text is not null, a loop is performed for each element in the people list to check if the person’s name or age contains text (query).
By default, the contains() function is sensitive to the case and order of characters in the query. When a match is found, the current person is added to a new list as discussed in step (H) above. If no match is found, a toast is shown indicating the same.
In our scenario, the list is relatively small making it suitable to update the RecyclerView after the loop. Otherwise we’d need to call updateRecyclerView() function each time a match is found.
v). updateRecyclerView() explained
This function is responsible for updating the RecyclerView once the check is done. Something a little fancy is that empty and null are not synonymous!
A length of zero is considered empty not null. This means that the search function will be called when the length of query text changes from 1 to 0.
The problem is that nothing will be filtered out and this will result in a 100% match, therefore a clone of the original list will be returned.
This is not always desired as it can lead to extreme memory consumption.
It can be avoided by doing either of the following:
- Restricting the search function to only run when the length of the query is greater than zero.
- Disabling onQueryTextChange() method by keeping its body empty.
Finally this is how the app should look like:
Conclusion
In this tutorial, we have learned how to create and use a SearchView to filter data in a RecyclerView in Android. This is a good way to improve the overall performance of the application.
The source code for this tutorial can be found in this GitHub repository.
Peer Review Contributions by: Peter Kayere
About the author
Eric Gacoki is a 2nd-year undergraduate student pursuing computer science. He is a self-taught and solution-driven Android software developer. Currently, he’s doubling up as a co-lead in Android Stack under Developer Students’ clubs (sponsored by Google) in his university. He enjoys teaming up with all levels of developers to solve complex problems and learning from each other.
Want to learn more about the EngEd Program?
Discover Section’s community-generated pool of resources from the next generation of engineers.
Источник
Русские Блоги
Использование SearchView в Android
Уважаемые одноклассники, я снова здесь и готов к вождению. , ,
Я не знаю, что вы обычно используете для прослушивания музыки, мне лично нравится NetEase Cloud Music (Не реклама, но что я делаю?), но теперь NetEase Cloud Music не может остановить песню Джея Чоу, это немного. , , В тот день я неожиданно подумал о MaterialDesign, который я недавно изучал, и о том, как реализована строка заголовка NetEase Cloud Music. Позже я использовал различные Baidus, и мои усилия окупились. Я наконец-то понял это! На самом деле, NetEase Cloud Music использует SearchView, упомянутый в заголовке, который фактически является поисковым. Так как это достигается? Пожалуйста, послушайте разложение в следующий раз!
[Загрузка изображений за пределы сайта . (image-41ace8-1524489658384)]
Шучу, студенты готовы и сразу поехали. , ,
Очки знаний в этой статье
- Введение в SearchView
- Реализуйте функцию поиска в NetEase Cloud Music
- Реализация базовой функции поиска
- Украшение страницы
- Некоторые общие проблемы
Позвольте мне кратко объяснить, здесь в основном объясняется, как SearchView реализует строку заголовка NetEase Cloud Music, но все они основаны на Панели инструментов, если вы мало знаете о Панели инструментов и меню!
Пожалуйста, смотрите эти две статьи на моем публичном аккаунте (сильная волна выхода)
Выше подробно объяснено использование и меры предосторожности панели инструментов и меню! ! !
1. Введение в SearchView
SearchView — это элемент управления поиском, который связан с панелью инструментов и задается через меню (я не знаю, можете ли вы понять, как я его обобщил). Кнопка поиска появится в правой части панели инструментов (система поставляется с ней, вы также можете заменить ее). Когда вы нажмете кнопку поиска, появится соответствующее окно редактирования для поиска. При нажатии на крестик этот поиск отменяется, а кнопка поиска восстанавливается.
2. Функция поиска NetEase Cloud Music
2.1 Базовая реализация функции поиска
Вот некоторые изменения в меню, поэтому оно может не совпадать с вашим базовым эффектом, но я опубликую соответствующий контент, чтобы оно было удобно для ленивых больных раком, таких как я, и могло быстро достичь эффекта. В конце концов, когда проект разработки плотный, мне все равно, как его достичь! ! ! Сначала посмотрите на рендеринг основных функций
[Загрузка изображений за пределы сайта . (image-35b1ae-1524489658384)]
Я считаю, что если вы прочтете две предыдущие статьи, вы скоро сможете написать строку заголовка ниже.
- Код файла меню
- Код файла макета
- Код в деятельности
Запустите приведенный выше код, и тогда вы сможете увидеть вышеуказанный контент!
2.1.1 Инициализация и мониторинг кнопки поиска
Потому что, когда вы инициализируете SearcheView, вам нужно работать с соответствующим меню, поэтому оно обычно будет в onCreateOptionsMenu(Menu menu) Получить его в. Конкретный код выглядит следующим образом:
Обратите внимание, что это также может быть использовано при инициализации SearchView MenuItemCompat.getActionView(searchItem); Приобретение только устарело. , , Так что не говорите, что не знаете, видите ли вы это
- Соответствующий монитор setOnQueryTextListener(OnQueryTextListener listener)
Может ли вышеуказанный контент реализовать простой поиск? На самом деле я лично считаю, что этого мало? Почему ты это сказал? Поскольку вы хотите контролировать переключение фрагментов, нет соответствующей временной точки или нет времени для переключения фрагментов. Я долго думал об этом. Позже, когда я увидел исходный код, я обнаружил, что время проекта Google на самом деле Я уже думал об этом для нас. На самом деле, я думаю, что мы можем думать, инженеры Google поймут это для нас!
- setOnSearchClickListener (OnClickListener listener) Метод для обратного вызова при нажатии значка поиска.
- setOnCloseListener (OnCloseListener listener) Метод для обратного вызова при переходе после поиска.
Таким образом, есть соответствующий момент времени. Когда вы входите, открываете вещь и вставляете фрагмент (здесь, если вы хотите добавить эффекты анимации, вы можете использовать ViewPager, а затем переключиться, установив метод для отображения этого. На самом деле, вещи тоже Вы можете установить анимацию, это зависит от того, как вы выберете). Когда вы нажимаете закрыть. Просто замените предыдущий фрагмент. Чтобы все лучше поняли, позвольте мне реализовать это в коде! Давайте посмотрим на эффект (виртуальная машина немного глупа!)
- На самом деле никаких изменений в xml нет, поэтому я не буду публиковать их!
- Код в Activity является наиболее важным, код выглядит следующим образом:
Здесь важнее всего эти мониторы. Пока вы понимаете мониторы, в принципе проблем не будет.
Таким образом, соответствующий эффект может быть достигнут. как насчет этого? Не плохо, верно! ! !
2.2 Украшение интерфейса
2.2.1 Текст приглашения по умолчанию
Приведенное выше изображение отображается, когда текст подсказки отсутствует. Как добавить текст подсказки?
Вы можете добавить текст запроса поиска через вышеуказанный код.
2.2.2 Кнопка поиска не исчезает
Эта кнопка поиска находится внутри поля ввода.При настройке содержимого кнопка поиска исчезнет. Я чувствую, что то, что я описал, не правильно, что с ним? Пока ты понимаешь. , ,
- setIconifiedByDefault (boolean iconified) Этот Api в основном контролирует, находится ли кнопка поиска внутри поля ввода, true означает, что она отображается внутри, а false означает, что она отображается снаружи
2.2.3 Кнопка поиска, чтобы отменить проблему закрытия значка
У некоторых менеджеров по продукту всегда есть странные потребности и они хотят убрать крест после поиска. Скажи бесчеловечность. , , Может быть изменено только тихо. , , На самом деле, мое сердце разбито. , ,
- onActionViewExpanded () устанавливает API, чтобы значок закрытия не отображался
Хотя вы можете отключить этот значок, в этом случае есть проблема: операция отключения и переключения фрагмента, записанного ранее, будет здесь недействительной. Как это решить? Подумав об этом в течение долгого времени, мне нужно иметь дело только с событием возврата, или у меня нет возможности узнать, когда пользователь действительно, когда поиск завершен? Только тогда, когда будет выполнена операция возврата и когда она закончится!
Добавьте этот код, получите onDloseClicked () SearchView через отражение, просто вызовите его
2.2.4 Расширение панели поиска по умолчанию
Продукт снова сказал. Когда вы входите на эту страницу, диалоговое окно поиска должно отображаться по умолчанию. Пользователю требуется на одну операцию меньше и удобство работы. Я сказал в то время. Как насчет пользователя? Продукт говорит, что такой странный пользователь не заботится. , , (Я был в то время! Моя голова была полна черных линий)
- setIconified (boolean iconify) Установить, будет ли расширено поле ввода поиска, обратите внимание здесь! false означает расширенный, true означает закрытый
2.2.5 Изменить значок поиска или удалить значок
Продукты Laogen не собираются работать! Я посмотрел на значок поиска и подумал, что он маленький, я хочу изменить его! Как это сделать?
В теме Активность на странице, добавьте соответствующийsearchViewStyleСвойство, это свойство может быть установлено самостоятельно.
Изображение здесь зависит от вашей игры. , ,
2.2.6 Изменить цвет текста
Если вы считаете, что текст в поле ввода или текст приглашения выглядят чёрно-черными, вы можете изменить его следующим образом.
Я не знаю, есть ли что-нибудь еще. Я думаю, этого достаточно, чтобы иметь дело с вашими менеджерами по продукту. Вы не можете положить нож на стол или положить QR-код или что-то еще. , ,
Я надеюсь, что моя статья будет полезна для вас! Надеюсь, мы добьемся прогресса вместе. , , увидимся!
Источник