Android spinner select all

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(), а затем уже и позицию.

Читайте также:  Pokemon x rom citra android

Тонкая настройка — своя разметка для 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 selection

The OnItemSelectedListener event handler gets called both when a spinner selection is changed programmatically, and when a user physically clicks the spinner control. Is is possible to determine if an event was triggered by a user selection somehow?

Or is there another way to handle spinner user selections?

8 Answers 8

To workaround you need to remember the last selected position. Then inside of your spinner listener compare the last selected position with the new one. If they are different, then process the event and also update the last selected position with new position value, else just skip the event processing.

If somewhere within the code you are going to programatically change spinner selected position and you don’t want the listener to process the event, then just reset the last selected position to the one you’re going to set.

Yes, Spinner in Android is painful. I’d even say pain starts from its name — «Spinner». Isn’t it a bit misleading? 🙂 As far as we’re talking about it you should also be aware there’s a bug — Spinner may not restore (not always) its state (on device rotation), so make sure you handle Spinner’s state manually.

Hard to believe that a year and a half later, the problem still exists and continues to boggle people.

Thought I’d share the workaround I came up with after reading Arhimed’s most useful post (thanks, and I agree about spinners being painful!). What I’ve been doing to avoid these false positives is to use a simple wrapper class:

All it does is trap item selected events for the same position that was already selected (e.g. the initial automatically triggered selection for position 0), and pass on other events to the wrapped listener. To use it, all you have to do is modify the line in your code that calls the listener to include the wrapper (and add the closing bracket of course), so instead of, say:

Читайте также:  Как включить будильник android

Obviously once you’ve tested it, you could get rid of the Log calls, and you could add the ability to reset the last position if required (you’d have to keep a reference to the instance, of course, rather than declaring on-the-fly) as Arhimed said.

Hope this can help someone from being driven crazy by this strange behaviour 😉

In the past I’ve done things like this to distinguish

Then in textBox’s listener

I use ++ and — rather than setting a boolean value to ‘true’ so that there is no worry when methods nest other methods that might also set the internal change indicator.

I had this situation lately when using spinners and the internet didn’t came up with a suitable solution.

My application scenario:

X spinners (dynamically, 2 for each cpu, min & max) for setting & viewing the CPU-Frequency. They are filled when the application starts and they also get the current max/min freq of the cpu set. A thread runs in the background and checks for changes every second and updates the spinners accordingly. If a new frequency inside the spinner is set by the user the new frequency is set.

The issue was that the thread accessed setSelection to update the current frequency which in turn called my listener and I had no way of knowing if it was the user or the thread that changed the value. If it was the thread I didn’t want the listener to be called since there would have been no need to change the frequency.

I came up with a solution that suits my needs perfectly and works around the listener on your call 🙂 (and I think this solution gives you maximal control)

I extended Spinner:

and created my own OnItemSelectedListener:

If you now create a MySpinner you can use this to set the selection:

Where callListener is either true or false. True will call the listener and is default, which is why user interactions are getting identified, false will also call the listener but uses code you want for this special case, exempli gratia in my case: Nothing.

I hope that someone else finds this useful and is spared a long journey to look if something like this already exists 🙂

Источник

Android Spinner: Get the selected item change event

How can you set the event listener for a Spinner when the selected item changes?

Basically what I am trying to do is something similar to this:

17 Answers 17

Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:

A spinner does not support item click events. Calling this method will raise an exception.

This works for me.

Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.

Note: Remember one thing.

Spinner OnItemSelectedListener event will execute twice:

  1. Spinner initialization
  2. User selected manually

Try to differentiate those two by using flag variable.

Читайте также:  Как освободить память облако андроид

You can implement AdapterView.OnItemSelectedListener class in your Activity.

And then use the below line within onCreate()

Then override these two methods:

You can avoid the OnItemSelectedListener() being called with a simple check: Store the current selection index in an integer variable and check within the onItemSelected(..) before doing anything.

Of cause the iCurrentSelection should be in object scope for this to work!

Find your spinner name and find id then implement this method.

It doesn’t matter will you set OnItemSelectedListener in onCreate or onStart — it will still be called during of Activity creation or start (respectively).
So we can set it in onCreate (and NOT in onStart!).
Just add a flag to figure out first initialisation:

then in onCreate (or onCreateView) just:

The docs for the spinner-widget says

A spinner does not support item click events.

You should use setOnItemSelectedListener to handle your problem.

For kotlin you can use:

Note: for parameters of onItemSelected method I use custom variable names

take a global variable for current selection of spinner:

If you want a true onChangedListener(). Store the initial value in the handler and check to see if it has changed. It is simple and does not require a global variable. Works if you have more than one spinner on the page.

Objects are your friend, use them.

This will work intialize the spinner and findviewbyid and use this it will work

By default, you will get the first item of the spinner array through

whenever you selected the value in the spinner this will give you the selected value

if you want the position of the selected item then do it like that

the above two answers are for without applying listener

The best way what I think would be to have an flagitemselected = 0; in onCreate() . And on item selected event increment that flag i.e flagitemselected++ ; and then check

This will help I guess.

One trick I found was putting your setOnItemSelectedListeners in onWindowFocusChanged instead of onCreate. I haven’t found any bad side-effects to doing it this way, yet. Basically, set up the listeners after the window gets drawn. I’m not sure how often onWindowFocusChanged runs, but it’s easy enough to create yourself a lock variable if you are finding it running too often.

I think Android might be using a message-based processing system, and if you put it all in onCreate, you may run into situations where the spinner gets populated after it gets drawn. So, your listener will fire off after you set the item location. This is an educated guess, of course, but feel free to correct me on this.

I know this was long solved but I have a «Please select» string at the top of my string arrays. Then when you write the listener

You can of course extend the when statement to have different responses or actions.

Not the answer you’re looking for? Browse other questions tagged android events spinner android-spinner or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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