- Spinner
- Общая информация
- Используем адаптер
- В закрытом состоянии
- В раскрытом состоянии
- За честные выборы! — что выбрал пользователь
- Предупредить компонент об изменении пунктов
- Найти позицию по слову
- Тонкая настройка — своя разметка для Spinner
- spinner.xml
- spinner_dropdown_item.xml
- Программная настройка цвета и размера текста для первой строчки
- Не выбирать элемент при запуске
- CustomAdapter.java
- Режим android:spinnerMode=»dialog»
- Android: Spinner customizations
- Custom Spinner
- Adjusting the Spinner widget
- Adapter
- Drawbacks
- Custom Spinner implementation
- Android Custom Spinner With Image And Text | Custom Adapter
- Look And Feel
- Step 1. Custom Layout
- Step 2. Add Fruit Images
- Step 3. Custom Adapter
- Step 4. Last Writings
- Explanation of Above Code
Spinner
Общая информация
Компонент Spinner из раздела Containers (раньше был в разделе Widgets) похож на выпадающий список (ComboBox), используемый в OC Windows (не путать с игрушкой Fidget Spinner). В закрытом состоянии компонент показывает одну строчку, при раскрытии выводит список в виде диалогового окна с переключателями.
Сначала покажу быстрый способ использования элемента. При добавлении элемента на экран отображается просто полоска со строкой Item1. В основном настройка происходит программным путём. Но можно и через XML. Добавим в строковый файл ресурсов strings.xml несколько элементов массива:
Теперь осталось в атрибуте android:entries указать на созданный массив и компонент Spinner будет заполнен данными. Запустите проект и проверьте.
Цвет компонента можно задать в атрибуте android:background=»@color/colorAccent».
Внешний вид компонента в разных версиях Android менялся.
Если нужно из программы узнать, какой пункт из выпадающего списка выбран в Spinner, то можно использовать такой код, например, при нажатии кнопки:
Если нужен не текст, а номер позиции, то вызывайте метод getSelectedItemPosition()
Если вам нужно получить выбранный элемент сразу в момент выбора, то используйте метод setOnItemSelectedListener(), который описан ниже.
Используем адаптер
Как и в случае с компонентом ListView, Spinner использует адаптер данных для связывания содержимого из набора данных с каждым пунктом в списке. Для загрузки данных нужно:
- Получить экземпляр компонента Spinner
- Настроить адаптер данных для связывания
- Вызвать метод setAdapter()
В закрытом состоянии
В раскрытом состоянии
Данные в закрытом и раскрытом состоянии Spinner отображает по разному. Поэтому необходимо создавать макеты шаблонов для обоих состояний. Android предоставляет несколько своих собственных ресурсов для Spinner для простых задач. Например, есть ресурс android.R.layout.simple_spinner_item для создания представления для каждого элемента списка. Ресурс android.R.layout.simple_spinner_dropdown_item служит шаблоном для раскрывающего списка.
Создадим строковый массив в файле strings.xml:
Загрузим строковый массив с именем animals в экземпляр класса ArrayAdapter при помощи метода createFromResource():
Запустив программу, вы увидите работающий пример, как на картинках, представленных выше.
По умолчанию выводится первый элемент списка. С помощью метода setSelection() можно установить нужный элемент по умолчанию, указав индекс из строкового ресурса.
За честные выборы! — что выбрал пользователь
Нам интересно узнать, что именно выбрал пользователь из списка и обработать эту информацию.
Нам нужно получить выбранный пользователем пункт в компоненте Spinner при помощи метода setOnItemSelectedListener() и реализовать метод onItemSelected() класса AdapterView.OnItemSelectedListener:
Теперь при выборе любого пункта вы получите всплывающее сообщение о выбранном пункте. Обратите внимание, что нам также пришлось реализовать вызов обратного вызова onNothingSelected().
В начале статьи показывался более простой способ с использованием метода getSelectedItem(), который достаточен для большинства случаев.
Предупредить компонент об изменении пунктов
Если в приложении вы изменили состав выпадающего списка, то необходимо сообщить компоненту Spinner, чтобы он показывал обновлённый список. Сделать это можно при помощи метода адаптера notifyDataSetChanged().
Найти позицию по слову
Если мы хотим узнать, в какой позиции находится то или иное слово, то нужно получить адаптер через метод getAdapter(), а затем уже и позицию.
Тонкая настройка — своя разметка для Spinner
Вы можете установить собственный фон, но не можете установить, к примеру, цвет и размер текста в настройках свойств. В предыдущих примерах мы видели, что при подключении к адаптеру используются системные разметки android.R.layout.simple_spinner_item и android.R.layout.simple_spinner_dropdown_item. Ничто не мешает вам посмотреть исходники данных файлов и создать файлы для собственной разметки, которые потом можно подключить к адаптеру.
Давайте создадим собственную разметку с значками. В папке res/layout создаём файл row.xml:
Осталось в коде заменить две строки на одну:
В примере использовался один общий файл, но можете создать два отдельных шаблона для закрытого и раскрытого вида элемента. Например, так (простейший вариант):
spinner.xml
spinner_dropdown_item.xml
В принципе, вы можете установить свой значок для каждого пункта, вам нужно создать свой адаптер под свои нужды. Создадим новый класс на основе ArrayAdapter и реализуем задачу. Теперь у двух любимых дней недели будет выводиться лапочка.
Программная настройка цвета и размера текста для первой строчки
В сети нашёл пример программной установки цвета и размера текста для первой строчки элемента в закрытом состоянии. Может кому пригодится.
Не выбирать элемент при запуске
Иногда хочется, что при запуске не выбирался первый элемент списка, как это происходит по умолчанию. Решение в лоб — добавить первым элементом пустую строку или текст «Выберите. » не слишком красив, так как при раскрытии списка мы увидим эти элементы, которые только портят картину. В сети нашёл вариант, использующий собственный адаптер.
CustomAdapter.java
Попробуйте этот вариант, может он подойдёт вам.
Режим android:spinnerMode=»dialog»
У компонента есть атрибут android:spinnerMode, у которого можно установить значение dialog. В этом случае при раскрытии списка задняя активность затемняется. Это хорошо заметно на белом фоне. Проверьте самостоятельно.
В этом режиме диалога для компонента Spinner можно вывести заголовок с помощью методов setPrompt() или setPromptId(). Заголовок выводится при раскрытии списка.
Источник
Android: Spinner customizations
Implement Android dropdown just the way you want.
Custom Spinner
In this article, I’ll describe two ways to achieve custom spinner for country selection that I had to implement at InCharge app. We officially support now 4 countries with charging stations, each country has specific legal rules, terms & conditions, etc.
The screen mockups I received from our designer were exactly these:
So the design for selection was not looking as a default Android Spinner as it had a header included when going to dropdown mode. Is it possible to implement using Spinner Widget? Let’s see.
Adjusting the Spinner widget
OK, so let’s begin with implementing layout:
And add a Spinner widget:
In this way, we’ve just built a Spinner widget on our UI. Thanks to tools:listitem=»@layout/item_country» we can see in Android Studio Designer how the Spinner will look like and adjust paddings/margins properly 🙂
With property android:background we can add a blue outline when Spinner is in the selected state and with android:popupBackground the background of dropdown view — easy so far.
Adapter
The magic of adding header will be done in our CountryAdapter class:
And an enum for supported countries is realized like this:
There are several parts that need to be explained…
Firstly, let’s see that getView() method will build UI when Spinner is in idle state and getDropDownView() will build particular items when Spinner dropdown gets opened. This is a place where we need to expect position == 0 to build a header with «Select option».
Unfortunately, there is no Spinner public method to programmatically close the dropdown. So how could we close it, when the header item gets clicked? There are couples of hacks to overcome this problem and here is one of them:
so we pretend as if the BACK button got clicked. Yeah, hacky…
Also to prevent selections for header view and not trigger its Spinner behavior we override isEnabled method to return false in this case.
Drawbacks
So we were able to implement the expected design somehow. But is it an ultimate solution? We had to use a hack with closing dropdown and make code dirty. Also, what if the designer suddenly changes his mind and wants to apply some animation for example arrow rotation? Built-in popup has entered animation which might interrupt these animations.
Technically android:popupAnimationStyle is applicable to Spinner style but it’s from SDK 24, quite high, right?
Would there be another solution?
Custom Spinner implementation
If we look into the Android source code of Spinner, we will see that underneath a PopupWindow is used to render the dropdown. Implementing classes are private so we cannot use them. But how much work could that be to make it yourself? Let’s try!
Let’s replace Spinner widget with anything else that could include item_country.xml Now, in setOnClickListener < . >part (trying to override OnClickListener on Spinner would result in RuntimeException).
So here we handle dropdown view by ourselves. We have full control of its UI! I chose ListView, could be anything else! All rendered by layout_country_dropdown.xml .
Note that you can use the very same CountryAdapter but rename the getDropDownView() method to getView() , and get rid of existing getView() .
Thus… Not a lot of work was required to transition 8) That’s what we all love. This solution seems way cleaner, with no dirty hacks — just add popupWindow?.dismiss() when header clicked. How does it look like?
What about animation management? It’s easy. We could set custom animation for a PopupWindow or simply disable it with a parameter:
then in CountryAdapter on header item creating add something like:
And the result is:
Try writing rotation animation on dropdown close by yourself 😉
Источник
Android Custom Spinner With Image And Text | Custom Adapter
Android custom spinner with image And Text is a good idea for better user experience.
This tutorial will guide you to make custom spinner with custom adapter.
At the end of the tutorial, you will be able to make fully customize view for the spinner.
Adapter will inflate the custom view for the spinner and for the dropdown menu also.
You can showcase brief information about the items of the spinner using it’s image.
If you want to enhance the quality then spinner with image will give an extra delight to the user.
Look And Feel
Following images shows us how our spinner will look with images and texts.
First Screen
Drop Down
Last View Toast
Step 1. Custom Layout
In this step, we will create layout file that will represent the spinner’s view.
So, make a new layout resource file named spinner_custom_layout.xml
Add below source code in it
As you can see that the above layout file is purely custom and it does not include any default code or UI item.
You can set any UI widget like TextView, ImageView etc. as per your requirements.
Step 2. Add Fruit Images
Because we are making spinners with images, we need to add some images in the drawable folder.
Actually, you should add number of images which is equals to the number of items in the spinners.
Download the fruit images by clicking the below link
[sociallocker] Download Fruit Images [/sociallocker]
Now add these images into res-> drawable folder.
Step 3. Custom Adapter
We need to write custom adapter that will accept our custom layout file.
This adapter will create the custom view for our spinner using that spinner_custom_layout.xml file.
Following source code is for CustomAdapter.java file.
Let us dive deep into this adapter class.
In the Main Activity of this example I have defined two arrays as below
- First one is the string array which defines the names of the fruits.
- Second contains the resource id of the drawable images.
- In the constructor of the adapter, we will pass these two arrays as a parameter.
- So we will receive them here at the execution of the adapter class.
getView() method from adapter is the most important part of this class. Below is the code for it.
- getView() method will create a custom view for our spinner.
- It will inflate the spinner_custom_layout.xml file to create a particular view for the spinner.
After that, compiler will set the name and image of the fruit by using the string ( fruit[i] ) and integer ( images[i] ) array respectively.
Step 4. Last Writings
In this last step, you should update the code of your activity_main.xml and MainActivity.java file code
Replace the code of activity_main.xml with the below one
I have taken one spinner in this file.
Copy following code into MainActivity.java file
Explanation of Above Code
Look at the below two lines
- First line defines the string array. This string array includes the names of the fruits.
- Second line defines the integer array which includes the resource id of the images which we have inserted in the drawable folder.
- Above code will first define the object of the adapter class and then compiler will set the adapter to the spinner.
- We have to pass out string and integer arrays as a parameter when defining the object of the adapter.
After this, our spinner will be populated with images and texts.
To track the on click method of the spinner, read below code
- Here, I have set the code when the user will select any particular item from the spinner.
- A toast will be popped up when user selects the item.
This toast contains the position of the item in the spinner and also the name of the selected item.
Источник