- How to create a custom filtered adapter in Android
- Introduction
- The application
- The layout
- The backing data object
- The custom adapter
- The custom filter
- Using the custom adapter
- Custom Array Adapter for Drop-Down, AutoCompleteTextView and for Spinner
- Android Custom Elements : Customize as per need
- How to Implement?
- Using a Custom ArrayAdapter :
- Полный список
How to create a custom filtered adapter in Android
Παρ 05 Απρίλιος 2019
Introduction
Android offers a nice component named AutoCompleteTextView that can be used to auto-fill a text box from a list of values. In its simplest form, you just create an array adapter passing it a list of objects (that have a proper toString() method). Then you type some characters to the textbox and by default it will filter the results searching in the beginning of the backing object’s toString() result.
However there are times that you don’t want to look at the beginning of the string (because you want to look at the middle of the string) or you don’t want to just to search in toString() method of the object or you want to do some more fancy things in object output. For this you must override the ArrayAdapter and add a custom Filter.
Unfurtunately this isn’t as straightforward as I’d like and I couldn’t find a quick and easy tutorial on how it can be done.
So here goes nothing: In the following I’ll show you a very simple android application that will have the minimum viable custom filtered adapter implementation. You can find the whole project in github: https://github.com/spapas/CustomFilteredAdapeter but I am going to discuss everything here also.
The application
Just create a new project with an empty activity from Android Studio. Use kotlin as the language.
The layout
I’ll keep it as simple as possible:
You should just care about the AutoCompleteTextView with an id of autoCompleteTextView.
The backing data object
I’ll use a simple PoiDao Kotlin data class for this:
I’d like to be able to search to both name, city and category_name of each object. To create a list of the pois to be used to the adapter I can do something like:
The custom adapter
This will be an ArrayAdapter
implementing also the Filterable interface:
You’ll see that we add an instance variable named mPois that gets initialized in the start with allPois (which is the initial list of all pois that is passed to the adapter). The mPois will contain the filtered results. Then, for getCount and getItem we return the corresponding valeus from mPois; the getItemId is used when you have an sqlite backed adapter but I’m including it here for completeness.
The getView will create the specific line for each item in the dropdown. As you’ll see the layout that is passed must have a text child which is set based on some of the attributes of the corresponding poi for each position. Notice that we can use whatever view layout we want for our dropdown result line (this is the layoutResource parameter) but we need to configure it (i.e bind it with the values of the backing object) here properly.
Finally we create a custom instance of the Filter, explained in the next section.
The custom filter
The getFilter creates an object instance of a Filter and returns it:
This object instance overrides two methods of Filter: performFiltering and publishResults. The performFiltering is where the actual filtering is done; it should return a FilterResults object containing a values attribute with the filtered values. In this method we retrieve the charSequence parameter and converit it to lowercase. Then, if this parameter is not empty we filter the corresponding elements of allPois (i.e name, city and category_name in our case) using contains. If the query parameter is empty then we just return all pois. Warning java developers; here the if is used as an expression (i.e its result will be assigned to filterResults.values).
After the performFiltering has finished, the publishResults method is called. This method retrieves the filtered results in its filterResults parameter. Thus it sets mPois of the custom adapter is set to the result of the filter operation and calls notifyDataSetChanged to display the results.
Using the custom adapter
To use the custom adapter you can do something like this in your activity’s onCreate:
We create the PoiAdapter passing it the poisArray and android.R.layout.simple_list_item_1 as the layout. That layout just contains a textview named text. As we’ve already discussed you can pass something more complex here. The thresold defined the number of characters that the user that needs to enter to do the filtering (default is 2).
Please notice that when the user clicks (selects) on an item of the dropdown we set the contents of the textview (or else it will just use the object’s toString() method to set it).
Posted by Serafeim Papastefanos Παρ 05 Απρίλιος 2019 android android, kotlin, adapter, filter
Источник
Custom Array Adapter for Drop-Down, AutoCompleteTextView and for Spinner
Android Custom Elements : Customize as per need
In Android development, any time we want to show a vertical list of scrollable items we will use a AutoCompleteTextView, MultiAutoCompleteTextView, Spinners and Any other Dropdown which has data populated using an Adapter . The simplest adapter to use is called an ArrayAdapter because the adapter converts an ArrayList of objects into View items loaded into the AutoCompleteTextView, MultiAutoCompleteTextView, Spinners and Any other Dropdown container.
The ArrayAdapter fits in between an ArrayList (data source of String) and the AutoCompleteTextView, MultiAutoCompleteTextView, Spinners and Any other Dropdown (visual representation) and configures two aspects:
- Which array to use as the data source for the list
- How to convert any given item in the array into a corresponding View object
CustomArrayAdapter is a single but All-In-one-Setup for all type of AutoCompleteTextView, MultiAutoCompleteTextView, Spinners and Any other Dropdown.
AutoCompleteTextView Control : A AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing. The list of suggestions is displayed in drop down menu.
MultiAutoCompleteTextView Control : A MultiAutoCompleteTextView is a view that is similar to AutoCompleteTextView, except that with a list of completion suggestions automatically while the user is typing. The list of suggestions is displayed in drop down menu offers suggestion for every token in the sentence. We can specify what is the delimiter between tokens like (“,”).
Using a Basic ArrayAdapter :
To use a basic ArrayAdapter , you just need to initialize the adapter and attach the adapter to the ListView. First, we initialize the adapter:
How to Implement?
Simple Steps and Points explain you how can you implement Original and Customize this Array Adapter by your own Good hand, and let you know there Basic Ideology behind this creation :
Like as shown Below :
The ArrayAdapter requires a declaration of the type of the item to be converted to a View (a String in this case) and then accepts three arguments: context (activity instance), XML item layout,and the array of data. Note that we’ve chosen simple_list_item_1.xml. which is a simple TextView as the layout for each of the items.
Now, we just need to connect this adapter to a AutoCompleteTextView to be populated:
Like as shown Below :
By default, this will now convert each item in the data array into a view by calling toString on the item and then assigning the result as the value of a TextView (simple_list_item_1.xml) that is displayed as the row for that data item. If the app requires a more complex translation between item and View then we need to create a custom ArrayAdapter instead.
Using a Custom ArrayAdapter :
1. Class Implementation:
Now this will help you in creating a custom class which extend ArrayAdapter Class to get there basic methods and function calls and code to put your custom views :
Step 1 : By Extending Array Adapter Class : This is a basic need you extending there class because it will provide you all basic needs:
You just need to Extend and need only one Constructor to Override you can leave rest of them for auto use.
Step 2 : Need to override basic methods :
These will help you handling customs clicks and custom item selection feature with FilterList and also getView() Method for your views customization :
Step 3 : Create ListFilter Class and Override its Method :
A filter constrains data with a filtering pattern. Filtering operations performed by calling CharSequence performed asynchronously. When these methods are called, a filtering request is posted in a request queue and processed later.
This will be enough with ArrayAdapter, now lets deep in Customization and make your Custom View like shown in screens :
Now our CustomArrayAdapter Class will be look like :
Step 4 : Basic variable Initialization to handle data at your Own :
Start with basic Global Variable Initialization with Class Private Specifiers :
Next lets complete some routine calls and changes those are basic in use like :
Step 5 : ItemLayout.xml File for Single Adapter Item View :
This will provide you your own custom xml creation for making your view what it look like :
Let me tell you my own custom Dimens and Colors implementation, you can change them as your own :
CardStyleDark file look like :
Step 6 : Implement view into ArrayAdpater List Item :
Now in this code : you can find how your custom view resource ItemLayout inflate and TextView itemTextView can get data from getItem(position), this will call again and again for new item upto array size of DataListItem just like onBindListener and OnCreateView of Recycler View and add your Item for View making.
Step 7 : Set ListFIter for Array Adapter basic operation :
Just like operation of matching your entry with list items, sort and filter your list according to AutoCompleteTextView and MultiAutoCompleteTextView.
This will be end of your complete implementation with Overall calls and code customization.
Compelete Code Look Like :
Now lets use this into your Own view :
Step 8: Now Lets call this into your Activity of Fragment with AutoCompleteTextView :
Step 9: Now Lets call this into your Activity of Fragment with MuliAutoCompleteTextView :
this will be the End with Coding now you can check your Code by Running this into Device or Emulator.
In this way, we have learnt how we can customize and code like a charm for own quality work into Each Element for making app like yours CustomArrayAdapter is a single but all in on setup for all type of AutoCompleteTextView, MultiAutoCompleteTextView, Spinners and Any other Dropdown.
If you have any problem than you can refer this video
For any queries please feel free to comment…!
Источник
Полный список
— создаем свой адаптер на основе BaseAdapter
Предоставляемые нам адаптеры универсальны и полезны, но иногда их возможностей не хватает для реализации задуманного. Тогда возникает необходимость написать свой адаптер. Попробуем и мы. Создавать будем не с нуля, а используя BaseAdapter.
Сделаем подобие интернет магазина. Будем выводить список товаров. Каждый пункт списка будет содержать название товара, цену и изображение. Также будет возможность отметить пункт галкой, поместив его тем самым в корзину.
Внизу списка сделаем кнопку, которая будет отображать содержимое корзины. В настоящем интернет-магазине мы повесили бы на нее, например, переход к созданию заказа.
Project name: P0541_CustomAdapter
Build Target: Android 2.3.3
Application name: CustomAdapter
Package name: ru.startandroid.develop.p0541customadapter
Create Activity: MainActivity
В файл strings.xml добавим текстовый параметр для названия кнопки.
layout для пункта списка – item.xml:
Чекбокс, пара текстовых полей и картинка.
Теперь пишем код. Можно все написать в MainActivity.java, но тогда он получится достаточно большим и неудобным для чтения. Я раскидаю весь код по трем классам.
Product.java – класс, описывающий товар:
Тут все просто – только конструктор и элементы класса. Не заморачиваюсь с доступом и методами Set/Get, чтобы не усложнять код.
BoxAdapter.java – созданный адаптер, который будем использовать
На всякий случай напомню общий принцип действия адаптера: он получает данные и выдает View для отображения пункта списка.
Смотрим код. В конструкторе мы заполняем наши внутренние переменные и получаем LayoutInflater для работы с layout-ресурсами. В objects у нас теперь хранится список товаров, которые надо отобразить в списке.
Методы, отмеченные аннотацией @Override, мы обязаны реализовать при наследовании BaseAdapter. Эти методы используются списком и должны работать корректно.
Метод getCount должен возвращать кол-во элементов. Мы возвращаем кол-во товаров.
Метод getItem должен возвращать элемент по указанной позиции. Используя позицию, получаем конкретный элемент из objects.
Метод getItemId должен возвращать id элемента. Здесь не заморачиваемся и возвращаем позицию. Кстати, также сделано в некоторых адаптерах. Поэтому мы и видели в обработчиках, что >
Метод getView должен возвращать View пункта списка. Для этого мы создавали layout-ресурс R.layout.item. В этом методе мы должны из R.layout.item создать View, заполнить его данными и отдать списку. Но перед тем как создавать, мы пробуем использовать convertView, который идет на вход метода. Это уже созданное ранее View, но неиспользуемое в данный момент. Например, при прокрутке списка, часть пунктов уходит за экран и их уже не надо прорисовывать. View из этих «невидимых» пунктов используются для новых пунктов. Нам остается только заполнить их данными. Это значительно ускоряет работу приложения, т.к. не надо прогонять inflate лишний раз.
Если же convertView в этот раз нам не дали (null), то создаем сами view. Далее заполняем наименования, цену и картинку из данных по товарам. Для чекбокса мы присваиваем обработчик, сохраняем в Tag позицию элемента и ставим галку, если товар уже в корзине.
Tag – это некое Object-хранилище у каждого View, куда вы можете поместить нужные вам данные. В нашем случае я для каждого чекбокса помещаю в его Tag номер позиции пункта списка. Далее в обработчике чекбокса я смогу этот номер позиции извлечь и определить, в каком пункте списка был нажат чекбокс.
В итоге, метод getView возвращает списку полностью заполненное view, и список его отобразит как очередной пункт.
Далее идет пара методов, которые не обязательно было создавать при наследовании BaseAdapter. Я их создал для удобства.
Метод getProduct – это аналог getItem, но он сразу конвертирует Object в Product. Он используется всего пару раз. И в принципе, можно было бы и без него обойтись.
Метод getBox проверяет, какие товары отмечены галками и формирует из них коллекцию-корзину.
myCheckChangeList – обработчик для чекбоксов. Когда мы нажимаем на чекбокс в списке, он срабатывает, читает из Tag позицию пункта списка и помечает соответствующий товар, как положенный в корзину.
Тут важно понимать, что без этого обработчика не работало бы помещение товаров в корзину. Да и на экране — значения чекбоксов в списке терялись бы при прокрутке. Потому что пункты списка пересоздаются, если они уйдут «за экран» и снова появятся. Это пересоздание обеспечивает метод getView, а он для заполнения View берет данные из товаров. Значит при нажатии на чекбокс, обязательно надо сохранить в данных о товаре то, что он теперь в корзине.
Остается накодить MainActivity.java:
Тут кода совсем мало.
В onCreate создаем адаптер и список.
В методе fillData генерируем данные для адаптера. В качестве картинки используем стандартную для всех пунктов. В идеале, для каждого товара своя картинка.
Метод showResult получает из адаптера список товаров корзины и выводит их наименования. Этот метод вызывается по нажатию кнопки на экране, т.к. прописан в ее свойстве onClick.
Все сохраняем и запускаем. Отмечаем товары и жмем кнопку для просмотра содержимого корзины.
Достаточно непростой получился пример из-за чекбокса.
Вполне может быть, что есть другой способ реализации этого примера. Но смысл был в том, чтобы показать создание своего адаптера. Для закрепления темы посмотрите еще этот гугловский пример.
На следующем уроке:
— используем Header и Footer в списках
— разбираемся, как и где используется HeaderViewListAdapter
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник