- Spinner
- Общая информация
- Используем адаптер
- В закрытом состоянии
- В раскрытом состоянии
- За честные выборы! — что выбрал пользователь
- Предупредить компонент об изменении пунктов
- Найти позицию по слову
- Тонкая настройка — своя разметка для Spinner
- spinner.xml
- spinner_dropdown_item.xml
- Программная настройка цвета и размера текста для первой строчки
- Не выбирать элемент при запуске
- CustomAdapter.java
- Режим android:spinnerMode=»dialog»
- Android Spinner Search Hint Prompt Text And Background Color
- Last Look
- Implementing Drop Down
- Step 1. Add Code in Default Activity
- Making Prompt Search Hint
- Step 1. Write XML code
- Add text using strings.xml
- Add Prompt text programmatically
- Changing Prompt Text And Background Color
- Spinner hint android studio
- About
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 Search Hint Prompt Text And Background Color
Android Spinner Search Hint Prompt Text And Background Color Example is for you.
You will learn to set prompt programmatically and to change prompt text and background color.
In android app, developer uses spinner to ask user to select any one choice from drop down menu or pop up dialog.
Here, you may want to give some hint or information to the user about your spinner options.
For example, if your spinner contains fruits as an options. Here, you can use some text like “Select Fruit” as a search hint.
Setting a search hint or prompt text in android spinner is not a tough task.
But customizing them like changing text color, changing background color need little tricks.
We will use two methods to implement search hint.
First by creating a drop down menu and second by using prompt dialog.
Last Look
Implementing Drop Down
Step 1. Add Code in Default Activity
First of all, make a new project in the android studio.
Choose “Empty Activity” after you have given project name and SDK version.
Add the below source code in activity_main.xml
- I have taken one spinner in main layout file.
- Set the spinner mode as a dropdown or just don’t write this line.
- By default, system will create drop down spinner only.
Write down the following coding lines in MainActivity.java file
Consider the below code snippet
- First line is creating a boolean variable. By default it has true value.
- Then, I have make one string array which contains the names of the fruits.
- In this string array, set your search hint at the first position.
Look at the following code
- Now above code will first set the adapter to the spinner.
- I have also implemented onItemSelectedListener for this spinner. Here, we will use that boolean variable (first).
- When the app is loaded for the first time on device, this compiler call this onItemSelectedListener. So it shows toast everytime when app is opened for fist time.
- This case is not ideal for user experience or user satisfaction.
So that, boolean variable (first) will help us to overcome this problem.
Making Prompt Search Hint
Step 1. Write XML code
Add the following code in activity_main.xml
So the final code for activity_main.xml is something like
- Here, I have taken three spinners to give them prompt text.
- All these spinners must have the following line
Now you can add prompt text using two methods.
- Directly add your text in strings.xml and use that string in activity_main.xml
- Add ans set the prompt text programmatically in spinner.
Add text using strings.xml
Write the below line in res->values->strings.xml file
Following snippet from activity_main.xml file using this text reference
Now add the below code in MainActivity.java
Write Above code before onCreate() method and write below code inside the onCreate() method
Add Prompt text programmatically
Add the spinner in the activity_main.xml
Now add the following in MAinActivity.java
Write above code above the onCreate() method and below inside onCreate()
Changing Prompt Text And Background Color
Below code from activity_main.xml will get prompt text programmatically.
Now we will learn how to change the color of prompt text and background.
- For this, we need to create a custom adapter and some layout files.
- We will create separate layout files for prompt text and drop down items (spinner options).
- So create a new xml layout file under res->layout directory
Give it a name like “vehicle_spinner.xml”
Code for “vehicle_spinner.xml” is as the following
- This file will create the layout interface for main spinner’s main or first look.
- Create another layout file under same directory named “vehicle_prompt.xml”
Write the below lines in it
- This file will generate the view structure for the prompt text.
- You can change the prompt text size, color, padding, margin etc. in this file.
- Make another layout file with the name vehicle_dropdown.xml
Source code for vehicle_dropdown.xml is as the following
- This will create a view for spinner options.
- Prepare a new java class named “CustomApinnerAdapter.java”
Write the below source code in “CustomApinnerAdapter.java”
- In the above code, getView() method creates a layout for default spinner look.
- In the getDropDownView() method, there are two scenarios.
- I have used two files to generate two different views.
- When the position is 0, means that for the very first time, we will use it as a prompt text creation.
- At this time, we will generate view using vehicle_prompt.xml file.
- In all other cases, (when position is not 0) we will generate drop down items which are spinner options, from which user will choose his desired option.
Following lines of coding are making a spinner with custom adapter
Источник
Spinner hint android studio
Android Hint Spinner
A hint spinner that allows showing a hint, similar to the HTML Select
You can use either a default or a custom layout.
Including the library
Add this dependency to your build.gradle file:
The HintSpinner class works as a container, binding a plain Android Spinner and a HintAdapter, which manages the hint. A callback is needed at the moment to skip the hint selected event, as otherwise it would have to be handled by the user (this might be optional in future versions).
All you need to do is to instantiate HintSpinner and call the init() method. This will automatically select the hint for you and bind the spinner to the adapter. You can select the hint again manually when you want, just calling the selectHint() method.
The HintAdapter class uses the default spinner layout by default and no extra configuration is required. You just need to instanciate the HintSpinner with the default layout constructor:
You can use whatever layout you want by overriding the HintAdapter#getCustomView() method. You can use any entity to store the data you want to show on your layout.
** 1.0 ** Initial version.
Sergio Rodrigo Royo
The MIT License (MIT)
Copyright (c) 2015 Sergio Rodrigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
A hint spinner that allows showing a hint, similar to the HTML Select
Источник