Android Spinner

Spinner can be defined as below –

"A spinner is a widget that have many options in dropdown, but only one option is displayed at a time. The displayed option is selected by the user. All the options in the spinner are provided using Adapter."

Note – You must provide an adapter with the some options so that user can pick one among them.

 

 

Now, we'll see different attributes that can be used to customise this widget.

S. No. XML Attributes Description
1 android:spinnerMode Use to set the display mode for spinner options.
2 android:gravity Specifies the position of the currently selected item.
3 android:popupBackground Use to set the background of the dropdown when spinnerMode is dropdown.
4 android:prompt Prompt to show when the spinner’s dialog is shown.
5 android:dropDownWidth Use to set width of the dropdown when spinnerMode is dropdown.
6 android:dropDownVerticalOffset Use this attribute to set vertical offset of the dropdown shown in the spinner.
7 android:dropDownSelector This is used as list selector when spinnerMode is dropdown.
8 android:dropDownHorizontalOffset Use this attribute to set horizontal offset of the dropdown shown in the spinner.

Attributes of Spinner are also inherited from AbsSpinner, ViewGroup and View. Some of the popular attributes of Spinner inherited from AbsSpinner are –

S. No. XML Attributes Description
1 android:entries Reference to an array resource that will populate the spinner.

Some of the popular attributes of Spinner inherited from ViewGroup are –

S. No. XML Attributes Description
1 android:clipChildren Defines whether a child is limited to draw inside of its bounds or not.
2 android:addStatesFromChildren Sets whether this viewGroup’s drawable state also include it’s children drawable states.
3 android:alwaysDrawnWithCache Specifies whether viewGroup’s children will be drawn using their drawable cache or not.
4 android:animateLayoutChanges Defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run.
5 android:animationCache Specifies whether layout animations should create a drawing cache for their children.

Some of the popular attributes of Spinner inherited from View are –


S. No. XML Attributes Description
1 android:id Sets unique id of the view. Note – Id of the view must always be unique in an xml file.
2 android:clickable Sets whether view is clickable or not.
3 android:elevation Sets base z-depth of the view.
4 android:background Sets background drawable of the view.
5 android:textAlignment Sets alignment of the text.
6 android:alpha Sets alpha of the view.
7 android:padding Sets padding of the view.
8 android:visibility Sets visibility(VISIBLE, INVISIBLE etc.) of the view.

Note – Visit official documentation for more details about attributes.

 

 

At First, we will create android application. Then, we're going to use android spinner in this application.

Follow the steps below to create new project. Please ignore the steps if you've already created a new project.

S. No. Steps
1 Open Android Studio.
2 Go to File => New => New Project. Write application name as Spinner. Then, click next button.
3 Select minimum SDK you need. However, we have selected 14 as minimum SDK. Then, click next button
4 Then, select Empty Activity => click next => click finish.
5 if you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to Create a New Project to know steps in detail.

Now, we're going to modify the xml and java file to use android spinner in the project.

Openres/values/strings.xml file. Then, add below code into it.

<resources>
<string name="app_name">Spinner</string>
<string name="selected_item">Selected item:</string>
</resources>

 

 

 

 

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

In activity_main.xml file, we have added spinner widget. Now, we're going to access this widget in the java file.

Open src/main/java/com.ukacademe.spinner/MainActivity.java file. Then, add below code into it.

package com.ukacademe.spinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String[] personNames = {"C", "C++", "C#", "JAVA", "JAVASCRIPT", "PHP", "ASP.NET"};
        Spinner spinner = findViewById(R.id.spinner);
        if (spinner != null) {
            ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, personNames);
            spinner.setAdapter(arrayAdapter);

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this, getString(R.string.selected_item) + " " + personNames[position], Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        }

    }
}

In MainActivity.java file, we have accessed spinner widget. Then, we created an adapter for the spinner and added it to the spinner. We also, display a toast message of selected item whenever any item is selected from the spinner dropdown.

Code inside src/main/AndroidManifest.xml file is as below –

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ukacademe.spinner">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

When you run the application, you will get output as shown below.

UKAcademe_Spinner