![]() |
VOOZH | about |
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 an Adapter, which efficiently binds a list of items to the Spinner widget. In this article, we will demonstrate how to programmatically create a Dynamic Spinner in the Kotlin language without setting up in the layout.
First we create a new project by following the below steps:
Note: To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Select Java or Kotlin as the programming language.
Here, we update the name of the application using the string tag. We also create the list of the items which will be used in the dropdown menu.
First, we declare a variable languages to access the strings items from the strings.xml file.
val languages = resources.getStringArray(R.array.Languages)then, we can create the spinner using the following code
val spinner = Spinner(this)
spinner.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)Add the spinner in the linear Layout using
val linearLayout :LinearLayout = findViewById(R.id.linear_layout)
linearLayout?.addView(spinner)