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.
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.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/imageView" android:layout_width="50dp" android:layout_height="50dp" android:padding="5dp" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp" android:layout_gravity="center" android:text="Custom Text" android:textColor="#000" /> </LinearLayout>
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.
import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView class CustomAdapter(internal var context: Context, internal var images: IntArray, internal var fruit: Array<String>) : BaseAdapter() { internal var inflter: LayoutInflater init { inflter = LayoutInflater.from(context) } override fun getCount(): Int { return images.size } override fun getItem(i: Int): Any? { return null } override fun getItemId(i: Int): Long { return 0 } override fun getView(i: Int, view: View?, viewGroup: ViewGroup): View { val view = inflter.inflate(R.layout.spinner_custom_layout,null) val icon = view.findViewById<View>(R.id.imageView) as ImageView? val names = view.findViewById<View>(R.id.textView) as TextView? icon!!.setImageResource(images[i]) names!!.text = fruit[i] return view } }
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.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
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.
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.Spinner import android.widget.Toast class MainActivity : AppCompatActivity() { internal var fruits = arrayOf("Apple", "Grapes", "Mango", "Pineapple", "Strawberry") internal var images = intArrayOf(R.drawable.apple, R.drawable.grapes, R.drawable.mango, R.drawable.pineapple, R.drawable.strawberry) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Getting the instance of Spinner and applying OnItemSelectedListener on it val spin = findViewById<View>(R.id.spinner) as Spinner spin.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText( this@MainActivity, "You Select Position: " + position + " " + fruits[position], Toast.LENGTH_SHORT ).show() } override fun onNothingSelected(parent: AdapterView<*>) { } } val customAdapter = CustomAdapter(applicationContext, images, fruits) spin.adapter = customAdapter } }
Now let us see some details about the above code file.
First of all, see the following
internal var fruits = arrayOf("Apple", "Grapes", "Mango", "Pineapple", "Strawberry") internal var images = intArrayOf(R.drawable.apple, R.drawable.grapes, R.drawable.mango, R.drawable.pineapple, R.drawable.strawberry)
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.
val spin = findViewById<View>(R.id.spinner) as Spinner spin.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText( this@MainActivity, "You Select Position: " + position + " " + fruits[position], Toast.LENGTH_SHORT ).show() } override fun onNothingSelected(parent: AdapterView<*>) { } }
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.