Custom spinner android kotlin

Android Spinner – Kotlin Example

Android Spinner in Kotlin

Android Spinner is a view that displays one child at a time and when user clicks on it, it lets the user pick among multiple values.

In this tutorial, we will learn how to create a Spinner in layout file, and how to set listener for the Spinner to serve user actions like clicking on the Spinner, selecting a value from Spinner, etc.

Code – Android Spinner

The following GIF shows how an Android Spinner looks, and how user could interact with it.

Android Spinner Code

A quick code snippet to use Android Spinner in layout and Kotlin file is as shown in the following respectively.

By default, the first element of the specified list is selected in the Spinner.

Following is a step by step guide of what is happening in the above code snippet to use Spinner

Step 1: Create a Spinner in layout file.

Step 2: Add AdapterView.OnItemSelectedListener to the interface list of your Activity.

Step 3: Prepare an array of elements to be shown in Spinner view.

Step 4: Set setOnItemSelectedListener to the Spinner.

Step 5: Create an ArrayAdapter with the list of items and default layouts.

Step 6: Set ArrayAdapter to Spinner.

Step 7: We have to override the following three methods of AdapterView.OnItemSelectedListener.

Example – Android Spinner

Following are the details of the Android Application we created for this example.

Application Name SpinnerExample
Company name tutorialkart.com
Minimum SDK API 21: Android 5.0 (Lollipop)
Activity Empty Activity

You may keep rest of the values as default and create Android Application with Kotlin Support.

activity_main.xml

MainActivity.kt

Output

Conclusion

In this Android Tutorial : Android Spinner – Kotlin Example, we have learnt to use Spinner with an example Android Application.

Источник

Kotlin Custom Spinner With Image And Text In Android

Kotlin Custom Spinner With Image And Text In Android Studio is the topic of this page.

Creating a custom spinner can help you to make greater look and feel of your android app.

According to your android app theme, sometimes you need to make custom colors and design for spinners. This tutorial will help you to achieve this feature.

You will also be able to show the image in the each option along with it’s name in the spinner.

First of all, see the below video for output representation.

Читайте также:  Android data доступ запрещен

Step 1. Proper Layout

For making custom look and feel of the spinner, we need to make separate layout XML file.

Spinner will inflate the view from this layout file. So go to app->res->layout file structure and make a new xml file with a name like spinner_custom_layout.xml

You should add the following coding lines in spinner_custom_layout.xml file.

There is one ImageView and one TextView in the above file.

Because our spinner’s every row will get the exact view of the above file, they all will have one ImageView and one TextView.

We can set any image and text in the above file Kotlin file as well. We will do this in the adapter file.

Step 2. Adapter Class

Create a new Kotlin file and give it a name like CustomAdapter.kt

Add the below source lines in CustomAdapter.kt file.

This adapter file will generate the every row’s view of the spinner.

getCount() method will return the number of rows or options in the spinner. It will calculate it using the integer Array “images

Now focus on the getView() method. In this method, compiler will first inflate the view using the xml layout file spinner_custom_layout.xml

Then it will find the image and name of the fruit using findViewById method.

After this, it will set the image in the ImageView and name in the TextView.

Step 3. Adding Fruit Images

Now it is time to add some fruit images in our project. Click on the below link to download the fruit images.

Go to app->res->drawable folder, insert all the fruit images in this drawable folder.

Step 4. Writing Last Lines

You should have two files when you have created a new android studio.

One is activity_main.xml and another is MainActivity.kt

Add the below source block inside activity_main.xml file.

You can see that I have added only one spinner in this XML layout file.

Now you should write down the below Code lines in MainActivity.kt file.

Now let us see some details about the above code file.

First of all, see the following

First line is making a variable with name “fruits“. This is the string array variable.

This “fruit” variable has the values like Apple, Grapes etc. fruit names in the string format.

Similarly, Second line is defining another variable but it is integer array. It’s name is “images

This “images” named integer array is containing the integer reference to the images available in the drawable folder.

We will use “fruits” string array variable to print names in the spinner row.

For printing or showing the fruit images inside every row of the spinner, we will use “images” integer array variable.

Читайте также:  Ксиаоми редми это смартфон или андроид

Now give your attention towards the below source block.

In first line, compiler will find the spinner using it’s id and a method “findViewById“.

Then after there is one code block. This code block will be run when the user interact with the spinner.

When the user opens the spinner and selects any option, compiler will run onItemSelectedListener() method.

This method will show one Toast to the user. Toast message contains the position of the selected option as well as the name and image of the fruit.

Compiler will call the onNothingSelected() method, when the user do not select any option from the spinner.

Источник

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 & Kotlin Examples code

Android kotlin tutorials and examples code for android apps developers.

custom spinner adapter android kotlin

android:id=»@+id/textViewCountryName»
android:layout_width=»0dp»
android:layout_height=»wrap_content»
android:layout_gravity=»center»
android:text=»Demo»
android:textColor=»#000″
android:padding=»7dp»
app:layout_constraintEnd_toEndOf=»parent»
app:layout_constraintHorizontal_bias=»0.5″
app:layout_constraintStart_toEndOf=»@+id/imageViewFlag»
app:layout_constraintTop_toTopOf=»parent»
app:layout_constraintBottom_toBottomOf=»parent»/>

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.item_custom_spinner.view.*

class CustomSpinnerAdapter(ctx: Context, countries: ArrayList ) : ArrayAdapter (ctx, 0, countries) <

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View <
return createItemView(position, convertView, parent);
>

override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View <
return createItemView(position, convertView, parent);
>

fun createItemView(position: Int, recycledView: View?, parent: ViewGroup):View <
val country = getItem(position)

val view = recycledView ?: LayoutInflater.from(context).inflate(
R.layout.item_custom_spinner,
parent,
false
)

country?.let <
view.imageViewFlag.setImageResource(country.flag)
view.textViewCountryName.text = country.countryName
>
return view
>
>

class CountryData (val countryName: String,
val flag: Int)

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() <

override fun onCreate(savedInstanceState: Bundle?) <
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val country_list = arrayListOf ()

country_list.add(CountryData(«India», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«United States», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«Indonesia», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«France», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«China», R.drawable.ic_flag_black_24dp))

val adapter = CustomSpinnerAdapter(
this,
country_list
)

spinner.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener <
override fun onItemSelected(parent: AdapterView ?, p1: View?, pos: Int, p3: Long) <
Toast.makeText(this@MainActivity, «» + (parent?.getItemAtPosition(pos) as CountryData).countryName, Toast.LENGTH_SHORT).show()
>

override fun onNothingSelected(p0: AdapterView ?) <
>
>)

// dynamically adding data after setting adapter to spinner

Источник

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