Custom spinner android studio

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. Ничто не мешает вам посмотреть исходники данных файлов и создать файлы для собственной разметки, которые потом можно подключить к адаптеру.

Читайте также:  Бесконтактная оплата доступна только при включенной защите android как ее включить

Давайте создадим собственную разметку с значками. В папке 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.

Читайте также:  Android vpn microsoft ras

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

Hi and welcome to another tutorial from Codingdemos, in this tutorial you will learn how create android custom spinner with images and text. The spinner will have a list of country names and flags, when you tap on any of the item an Android toast message will appear on the screen.

By the end of this article, we will have an app that looks like this. (Large preview)

In this tutorial we will be using the following:

    – Android studio version 2.3.3
    – Android emulator Nexus 5X with API 24
    – Minimum SDK API 16

1- Open up Android Studio and create a new project and give it a name, in our case we’ve named it (SpinnerImages), choose API 16 as the minimum SDK, then choose a blank activity, click “Finish” and wait for Android Studio to build your project.

2- Let’s create a new xml file and name it custom_spinner_row.xml , this file will have all the views that will be shown for each row inside Android spinner.

3- Inside custom_spinner_row.xml will have 2 Android textviews and 1 Android imageview, the 2 textviews will be used for country name and population while the imageview will be used for the country flag.

4- Open activity_main.xml file, here we will add an Android spinner.

5- Next we need to create a custom adapter, this adapter will be used to initialize the views inside custom_spinner_row.xml so that we can use it later with android spinner to show the data. Right click on the project package name com.codingdemos.spinnerimages → New → Java Class

Читайте также:  Лучшие анонимные чаты для андроид

6- I’ve named the custom adapter class as CustomAdapter.java . To be able to access the functions of ArrayAdapter we need to use extends with ArrayAdapter . Once you do that you will see a red line under the class name, hover your mouse over that error and Android Studio will warn you that you need to create a constructor.

Android custom adapter constructor. (Large preview)

How to create Android custom adapter constructor. (Large preview)

7- From Choose Super Class Constructor dialog box, choose the first option for the type of constructor ArrayAdapter(context:Context, resources:int)

8- Let’s modify the constructor by replacing resource parameter with 3 more parameters: String[]titles , int[]images and String[]population

9- We will need to override few methods: getCount , getView and getDropDownView

    – getCount : Return the number of items in the list. If you don’t override this method, the spinner list will be empty.
    – getView : This is where we work with initializing the views that we added them in the custom layout.
    – getDropDownView : This will show the data when you tap on Android spinner, if you don’t override this method your app will crash when you try to tap on the spinner.

10- Declare an inner class and name it ViewHolder , inside this class we will declare the views inside custom_spinner_row.xml

11- Inside getCount method we will return the number of titles inside the spinner

12- Let’s initialize the views inside getView method

13- Inside getDropDownView method we will return getView by passing the position, the view and the parent.

14- Now we are done with CustomAdapter.java class, next we will work with MainActivity.java class to initialize the spinner, spinner titles, images and population.

15- Declare and initialize the titles, images and population.

16- Initialize the spinner and the custom adapter

17- Allow the user to tap on the items in the spinner by using Spinner.setOnItemSelectedListener and show the selected item in an Android toast message.

18- Compile and run the app, you will see an android spinner being populated by country name, flag and it’s population.

19- One thing you will notice when you run the app, you will immediately see Android toast message containing spinner item appears on the screen without making any selection! To prevent that from happening, we need to override a method called onUserInteraction . This method is used to detect that the user have interacted with the device while the activity is still running.

20- Let’s override onUserInteraction

21- We will use the boolean variable isUserInteracting inside android spinner onItemSelected method to show the toast message.

22- Compile and run the app again, this time you will not see the spinner item shows up immediately on the screen thanks to onUserInteraction . The source code for the android custom spinner tutorial is available on Github. I hope you find this tutorial helpful and if you have any question please post them in the comment below.

4 Comments

It is very nice tutorial
how to control the size and margin of the drop down list?

Hi, you can change the width of the spinner by changing android:layout_width=»match_parent» to android:layout_width=»wrap_content» and you can also reduce the text and image size.

Very useful.
Not sure why you need the ViewHolder?
Surely if yo uhave the View then you can just get the child text and images and set them on thw view…

Источник

Оцените статью