- Android & Kotlin Examples code
- custom spinner adapter android kotlin
- Kotlin Custom Spinner With Image And Text In Android
- Step 1. Proper Layout
- Step 2. Adapter Class
- Step 3. Adding Fruit Images
- Step 4. Writing Last Lines
- Android Kotlin Custom Spinner DropDown With Image and Text
- Main XML Layout
- Model / Data Class
- Custom DropDown Adapter
- MainActivity
Android & Kotlin Examples code
Android kotlin tutorials and examples code for android apps developers.
custom spinner adapter android kotlin
android:id=»@+id/imageViewFlag»
android:layout_width=»40dp»
android:layout_height=»40dp»
android:layout_margin=»5dp»
app:layout_constraintEnd_toStartOf=»@+id/textViewCountryName»
app:layout_constraintHorizontal_bias=»0.5″
app:layout_constraintStart_toStartOf=»parent»
app:layout_constraintTop_toTopOf=»parent»
app:layout_constraintBottom_toBottomOf=»parent»/>
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)
android:id=»@+id/guidelineStart»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:orientation=»vertical»
app:layout_constraintGuide_begin=»16dp»/>
android:id=»@+id/guidelineEnd»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:orientation=»vertical»
app:layout_constraintGuide_end=»16dp»/>
android:id=»@+id/tv_selected_item»
android:layout_width=»0dp»
android:layout_height=»wrap_content»
android:layout_marginTop=»10dp»
android:hint=»Select Country from below spinner»
android:textColorHint=»#000000″
app:layout_constraintEnd_toEndOf=»@id/guidelineEnd»
app:layout_constraintStart_toStartOf=»@id/guidelineStart»
app:layout_constraintTop_toTopOf=»parent»>
ConstraintLayout
android:id=»@+id/cl_spinner»
android:layout_width=»0dp»
android:layout_height=»wrap_content»
android:layout_marginTop=»10dp»
android:background=»#ffffff»
android:padding=»5dp»
app:layout_constraintEnd_toEndOf=»@id/guidelineEnd»
app:layout_constraintStart_toStartOf=»@+id/guidelineStart»
app:layout_constraintTop_toBottomOf=»@id/tv_selected_item»>
android:id=»@+id/spinner»
android:layout_width=»match_parent»
android:layout_height=»wrap_content»
app:layout_constraintBottom_toBottomOf=»parent»
app:layout_constraintLeft_toLeftOf=»parent»
app:layout_constraintTop_toTopOf=»parent»/>
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)
setCustomAdapterSpinner()
>
fun setCustomAdapterSpinner()
val country_list = arrayListOfCountryData>()
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
country_list.add(CountryData(«Japan», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«New Zealand», R.drawable.ic_flag_black_24dp))
country_list.add(CountryData(«Other», R.drawable.ic_flag_black_24dp))
adapter.notifyDataSetChanged()
>
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.
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.
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) : 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(R.id.imageView) as ImageView? val names = view.findViewById(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.
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(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(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.
Android Kotlin Custom Spinner DropDown With Image and Text
Android Spinner Provides a quick way to select one value from a set , Touching the spinner displays all available value from which user can select one .
For loading data in spinner , I have kept json file inside asset folder and images inside drawable folder
Note : Here in this case («url») field in JSON is the name of image resource name kept in drawable folder ( as we are loading image from drawable into drop down layout )
File: app\src\main\assets\android_version.json
Folder : app\src\main\res\drawable
Main XML Layout
Model / Data Class
package com.tutorialsbuzz.customspinnerwithimagetext data class Model(val name: String, val url: String)
Custom DropDown Adapter
Create Custom Adapter this adapter will be used to set for spinner widget .
package com.tutorialsbuzz.customspinnerwithimagetext 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 CustomDropDownAdapter(val context: Context, var dataSource: List) : BaseAdapter() < private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View < val view: View val vh: ItemHolder if (convertView == null) < view = inflater.inflate(R.layout.custom_spinner_item, parent, false) vh = ItemHolder(view) view?.tag = vh >else < view = convertView vh = view.tag as ItemHolder >vh.label.text = dataSource.get(position).name val "drawable", context.packageName) vh.img.setBackgroundResource(id) return view > override fun getItem(position: Int): Any? < return dataSource[position]; >override fun getCount(): Int < return dataSource.size; >override fun getItemId(position: Int): Long < return position.toLong(); >private class ItemHolder(row: View?) < val label: TextView val img: ImageView init < label = row?.findViewById(R.id.text) as TextView img = row?.findViewById(R.id.img) as ImageView >> >
MainActivity
- Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
- Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml).
- Create a function readFromAsset (This method parse read json from asset folder parse and return List) .
- Create a instannce of CustomDropDownAdapter by passning context , List .
- Set the instannce of CustomDropDownAdapter to Spinner View.
package com.tutorialsbuzz.customspinnerwithimagetext import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.gson.Gson import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val modelList: List= readFromAsset() val customDropDownAdapter = CustomDropDownAdapter(this, modelList) spinner04.adapter = customDropDownAdapter > private fun readFromAsset(): List < val file_name = "android_version.json" val bufferReader = application.assets.open(file_name).bufferedReader() val json_string = bufferReader.use < it.readText() >val gson = Gson() val modelList: List = gson.fromJson(json_string, Array::class.java).toList() return modelList > >