- Spinner
- Общая информация
- Используем адаптер
- В закрытом состоянии
- В раскрытом состоянии
- За честные выборы! — что выбрал пользователь
- Предупредить компонент об изменении пунктов
- Найти позицию по слову
- Тонкая настройка — своя разметка для Spinner
- spinner.xml
- spinner_dropdown_item.xml
- Программная настройка цвета и размера текста для первой строчки
- Не выбирать элемент при запуске
- CustomAdapter.java
- Режим android:spinnerMode=»dialog»
- Kotlin Android Spinner Examples
- How to Define Spinner in Layout
- How to Populate Spinner
- Example 1: Kotlin Android Spinner – Get selected item
- Step 1: Create Project
- Step 2: Dependencies
- Step 3: Design Layout
- Step 4: Write Code
- Reference
- Example 2: Android Simple Spinner and OnItemSelected
- MainActivity.java
- SECTION 2 : Our Layout*
- Example 3: Kotlin Android Spinner – Fill From Array and ItemSelectionListener
- Kotlin Simple Spinner Example
- Resoources.
- Kotlin Code.
- (a)MainActivity.kt
- Example 4: Android Simple Spinner – Fill with List Of Objects
- Full Code
- Our Person Class
- SECTION 2 : Our MainActivity
- Resoources.
- Example 5: Android Spinner CRUD – ADD UPDATE DELETE
- Step 1 : Dependencies
- Step 2 : Create Helper Class
- CRUD Class
- Step 3: MainActivity
- Step 4: LAYOUTS
- ActivityMain.xml
- ContentMain.xml
- InputDialog.xml
- Oclemy
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(). Заголовок выводится при раскрытии списка.
Источник
Kotlin Android Spinner Examples
Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.
Spinner is an AdapterView. This means that it relies on an Adapter for its data.Adapters act as the bridge between adapterviews and the underlying data source.
This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.
Spinner is a concrete public class residing in the android.widget package.
Spinner is a public class that’s why we can access and use it.
Public classes are visible even from other packages apart from those they’ve been defined.
Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.
AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.
Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time. Spinner is an AdapterView. This means that it relies on an Adapter for its data.
Adapters act as the bridge between adapterviews and the underlying data source. This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.
Spinner is a concrete public class residing in the android.widget package.
Spinner is a public class that’s why we can access and use it.
Public classes are visible even from other packages apart from those they’ve been defined.
Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.
AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.
How to Define Spinner in Layout
We can use the Spinner object to specify the spinner in an xml Layout. This pattern of specifyng an Object in the Layout resource then referencing from the Java/Kotlin code is common in android as a platform and is also the one recommended.
How to Populate Spinner
Then in our java code we can first reference the Spinner from our Layout specification using the findViewById() method our activity class.
We can then instantiate a SpinnerAdapter(e.g ArrayAdapter). We use the default spinner Layout( android.R.layout.simple_spinner_item ).
We are using a static method called createFromResource(). This method is provided by the ArrayAdapter class and it returns us an ArrayAdapter instance from the external resource we provide it as our data source.
You have to make sure you’ve added string array into your strings.xml file:
ArrayAdapter provides us the createFromResource() method which gives us an instance of the ArrayAdapter from the string array we provided.
This method allows us specify the Layout the adapter will use to display the list of spinner choices. We use the one provided by the Android Platform.
Finally we set the adapter:
Let us now look at some full examples.
Example 1: Kotlin Android Spinner – Get selected item
Learn how to use spinner with this simple step by step example written in Kotlin.
We bind an aray to a spinner. Then when the user selects a single item in our spinner we show that selected item in a textview.
Step 1: Create Project
Start by creating an empty Android Studio project.
Step 2: Dependencies
No external dependencies are necessary.
Step 3: Design Layout
Add a spinner and a textview in your xml layout as follows. The textview will be used to render the selected spinner item:
activity_main.xml
Step 4: Write Code
In your MainActivity declare our TextView and Spinner:
Create an array of items to be bound to our spinner:
Pass those optionns to our ArrayAdapter then bind the adapter to the spinner:
The get the selected spinner item as follows, and display the selected item in the textview:
Here is the full code:
MainActivity.kt
Copy the code or download it in the link below, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Example 2: Android Simple Spinner and OnItemSelected
We have a look at android simple Spinner and see how to load data from a simple arraylist with help of arrayadapter.We also see how to handle ItemSelected events.
(a). Spinner – a DropDown Widget
2. How to Import Spinner
We use the import keyword:
2. How to Reference Spinner
We reference spinner using the findViewById() method.
(b). ArrayList – a collection
2. How to Instantiate an ArrayList
Here’s how, we use the new keyword:
3. How to add items to an ArrayList
We use the add() method. First we are clearing it to avoid duplicates.
MainActivity.java
SECTION 2 : Our Layout*
Example 3: Kotlin Android Spinner – Fill From Array and ItemSelectionListener
This is a tutorial for population of spinner from a Kotlin Array and handling the spinner’s itemSelection event.
Spinner is a widget, of course defined in the android.widget package and allows us render items in a dropdwon fashion.
In this tutorial we want to see how to set array of items in our spinner. Our programming language is Kotlin.
We also see how to retrieve the selected item and display them in a Toast.
Kotlin Simple Spinner Example
Here’s our example.
Let’s write some code.
Resoources.
Android platform provides a powerful and flexible way of adding static content as a resource.
These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.
Resources belong to a given type. These types can be:
- Drawable.
- Layout.
- Value.
Let’s start by looking at the layout resources
(a). activity_main.xml
This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.
We will do so inside the onCreate() method of Activity.
In our case we will make use of the following widgets and viewgroups:
- LinearLayout – Will arrange our TextView and Spinner linearly with TextView on top of Spinner.
- TextView – Will display the header text of our app.
- Spinner – Will render our data in dropdown fashion.
Kotlin Code.
Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.
In this class we are using Kotlin programming language.
We will have these classes in our project.
(a)MainActivity.kt
This is our launcher activity as the name suggests. This means it will be the main entry point to our app in that when the user clicks the icon for our app, this activity will get rendered first.
We override a method called onCreate() . Here we will start by inflating our main layout via the setContentView() method.
Our main activity is actually an activity since it’s deriving from the AppCompatActivity.
Example 4: Android Simple Spinner – Fill with List Of Objects
Hello guys.How do you do? This is what we do:
- Populate ArrayList with Person objects.
- Pass this ArrayList to our ArrayAdapter.
- Set our adapter to our Spinner
- Handle ItemSelection events,hence show a toast.
2. How to Import Spinner
First we imported Spinner from it’s android.widget pakage:
3. How to Reference spinner from Layout
Then referenced using the findViewById() of the Activity class:
(b). List – an Interface
2. How to use a java List
We use it and it’s implementer the ArrayList to hold our list of person Objects.
We’ve instantiated it and passed
Then cleared it:
and used the add() method to add Person objects:
(c). ArrayAdapter – an Adapter
We will use an ArrayAdapter instance to bind our data to our spinner.
2. How to Instantiate an ArrayAdapter
You pass:
- The Context
- The Resource
- The List
3. How to Bind Set an ArrayAdapter to a Spinner
You use the setAdapter() method.
Full Code
Let’s now look at the full source code.
Our Person Class
- Is our data object.
- Represents a single person with his properties.
SECTION 2 : Our MainActivity
Our main activity class.
Resoources.
Android platform provides a powerful and flexible way of adding static content as a resource.
These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.
Resources belong to a given type. These types can be:
- Drawable.
- Layout.
- Value.
Let’s start by looking at the layout resources
(a). activity_main.xml
SECTION 4 : Source Code Reference
GitHub : Source
Example 5: Android Spinner CRUD – ADD UPDATE DELETE
Android Simple Spinner CRUD tutorial. Hello.This is what we do in this example:
- Perform basic crud operations for a Spinner.
- We are using an arraylist as our data source.
- We add,update and delete.
Step 1 : Dependencies
No external dependencies are needed.
Step 2 : Create Helper Class
CRUD Class
- Perform adding,updating and deleting.
Step 3: MainActivity
- Launcher activity.
- ActivityMain.xml inflated as the contentview for this activity.
- Reference our adapterview,in this case our Spinner.
- Instantiate our ArrayAdapter and set it to our Spinner.
Step 4: LAYOUTS
ActivityMain.xml
ContentMain.xml
InputDialog.xml
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник