How to implement Spinner in Android Studio | Android Studio Tutorials

How to implement Spinner in Android Studio | Android Studio Tutorials


In this article we are going to learn "How to implement Spinner in Android Studio". We'll use default layout provided by Android Studio to implement our Spinner although we can use custom layouts also.

So let's start by making our MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="wrap_content"
        android:id="@+id/spinner"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"/>

</RelativeLayout>

We are going to implement our OnItemSelectedListener also to get which item we have selected.

MainActivity.java

package com.example.tutorialspecial;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
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 {
    Context context;
    Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        String[] array = {"Apple","Banana","Guava","Mango","Peach","Orange"};
        spinner = findViewById(R.id.spinner);
        ArrayAdapter adapter_sp = new ArrayAdapter(this,android.R.layout.simple_spinner_item,array);
        adapter_sp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter_sp);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }

}

Here in array we can add our values dynamically or statically all upto the user.

Feel free to ask doubts in comment section.

Happy Coding : )

Post a Comment

0 Comments