Dynamic Spinner in Android
Last Updated :
20 Jul, 2022
Many times in android applications we have to create any view dynamically without writing any XML code. For that, we can create our view using our Kotlin or Java file. In this article, we will take a look at How to Dynamically create a spinner in an android application. A sample video is given below to get an idea about what we are going to do in this article.
Note: This Android article covered in both Java and Kotlin languages.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating our linear layout-->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/idLLContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
Step 3: Working with the MainActivity file
Navigate to app > java > your app's package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.setPadding
class MainActivity : AppCompatActivity() {
// on below line we are creating a variable.
lateinit var languagesList: List<String>
lateinit var containerLL: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// on below line we are initializing our variables
languagesList = ArrayList()
containerLL = findViewById(R.id.idLLContainer)
// on below line we are adding languages
// to our language list
languagesList = languagesList + "Java"
languagesList = languagesList + "Kotlin"
languagesList = languagesList + "C++"
languagesList = languagesList + "C"
// on below line we are creating layout
// params for text view.
// and specifying width as match parent
// and height as wrap content
val txtLayoutParam = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
// on below line we are adding gravity
txtLayoutParam.gravity = Gravity.CENTER
// on below line we are creating layout params for spinner.
// and specifying width as wrap parent and height as wrap content
val spinnerLayoutParam = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
// on below line we are adding gravity
spinnerLayoutParam.gravity = Gravity.CENTER
// on below line we are creating our dynamic text view
val headingTV = TextView(this)
// on the below line we are setting for our text view.
headingTV.text = "Dynamic Spinner in Android"
// on below line we are updating text size.
headingTV.textSize = 20f
// on below line we are updating text color and font
headingTV.setTextColor(resources.getColor(R.color.black))
headingTV.typeface = Typeface.DEFAULT_BOLD
// on below line we are adding padding
headingTV.setPadding(20)
// on below line we are specifying text alignment.
headingTV.textAlignment = TextView.TEXT_ALIGNMENT_CENTER
// on below line we are adding layout
// param for heading text view.
headingTV.layoutParams = txtLayoutParam
//create spinner programmatically
val spinner = Spinner(this)
// on below line we are adding params for spinner.
spinner.layoutParams = spinnerLayoutParam
// on below line we are adding our views
// to container linear layout
containerLL.addView(headingTV)
containerLL.addView(spinner)
// on below line we are checking
// if spinner is not null
if (spinner != null) {
// on below line we are initializing
// and setting our adapter
// to our spinner.
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languagesList)
spinner.adapter = adapter
// on below line we are adding on item selected listener for spinner.
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View, position: Int, id: Long
) {
// in on selected listener we are displaying a toast message
Toast.makeText(
this@MainActivity,
"Selected Language is : " +
"" + languagesList[position], Toast.LENGTH_SHORT
).show()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
}
}
}
Java
package com.gtappdevelopers.kotlingfgproject;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// on below line we are creating variables.
private LinearLayout containerLL;
private ArrayList<String> languageList;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// on below line we are initializing our variables.
containerLL = findViewById(R.id.idLLContainer);
languageList = new ArrayList<>();
// on below line we are adding
// languages to our language list
languageList.add("Java");
languageList.add("Kotlin");
languageList.add("C++");
languageList.add("C");
// on below line we are creating layout params for text view.
// and specifying width as match parent and height as wrap content
LinearLayout.LayoutParams txtLayoutParam = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
// on below line we are adding gravity
txtLayoutParam.gravity = Gravity.CENTER;
// on below line we are creating layout params for spinner.
// and specifying width as wrap parent and height as wrap content
LinearLayout.LayoutParams spinnerLayoutParam = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
// on below line we are adding gravity
spinnerLayoutParam.gravity = Gravity.CENTER;
// on below line we are creating our dynamic text view
TextView headingTV = new TextView(this);
// on below line we are setting for our text view.
headingTV.setText("Dynamic Spinner in Android");
// on below line we are updating text size.
headingTV.setTextSize(20f);
// on below line we are updating text color and font
headingTV.setTextColor(getResources().getColor(R.color.black));
headingTV.setTypeface(Typeface.DEFAULT_BOLD);
// on below line we are adding padding
headingTV.setPadding(20, 20, 20, 20);
// on below line we are specifying text alignment.
headingTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
// on below line we are adding layout param
// for heading text view.
headingTV.setLayoutParams(txtLayoutParam);
// create spinner programmatically
Spinner spinner = new Spinner(this);
// on below line we are adding params for spinner.
spinner.setLayoutParams(spinnerLayoutParam);
// on below line we are adding our
// views to container linear layout
containerLL.addView(headingTV);
containerLL.addView(spinner);
// on below line we are checking if spinner is not null
if (spinner != null) {
// on below line we are initializing and setting our adapter
// to our spinner.
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, languageList);
spinner.setAdapter(adapter);
// on below line we are adding on item selected listener for spinner.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// in on selected listener we are displaying a toast message
Toast.makeText(MainActivity.this, "Selected Language is : " + languageList.get(position), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
}
Now run your application to see the output of it.
Output:
Similar Reads
Dynamic Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android.
7 min read
Dynamic TextSwitcher in Android
Text Switcher is a widget in android that contains multiple text views and we can display one text at a time in it. In this article, we will take a look at How to implement a Dynamic Text Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article.
8 min read
Dynamic Fragment in Android
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments a
4 min read
Contact Picker in Android
Contact Picker is a feature in android that a developer can use to ask users to select a particular contact. The developer can then query details related to the selected contact and perform the required action. A sample video is given below to get an idea about what we are going to do in this articl
7 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the c
4 min read
Dynamic ImageSwitcher in Android
Android ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. In this article, we will take a look at How to Create a Dynamic Image Switcher in Android. A sample video is given below to get an id
8 min read
Dynamic Splash Screen in Android
A Dynamic Splash screen is a more personalized image or graphic that is displayed when an application is loaded or launched. Dynamic Splash Screen consists of animation or moving graphics. It appears for a fraction of a second. It creates a sense of anticipation or excitement for the user and helps
3 min read
Dynamic Spinner in Kotlin
The Android Spinner widget is a UI component that is used to select from a drop down list. When the user taps the Spinner, it displays a dropdown list containing all available items. Upon selection, the Spinner updates to show the chosen value as the default. To provide a Spinner with data, we use a
3 min read
How to add Custom Spinner in Android?
Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app. Steps of Implementing Custom SpinnerStep 1: Create a new layout for each item in Spinn
5 min read
Slider Date Picker in Android
Slider Date Picker is one of the most popular features that we see in most apps. We can get to see this Slider date picker in most of the travel planning applications, Ticket booking services, and many more. Using Slider date Picker makes it efficient to pick the date. In this article, we are going
3 min read