How to add Custom Spinner in android?

25 Jun, 2020
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. If you want to know more about spinner in detail then click on this link.
Approach:
Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">      <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp"        android:src="@drawable/gfg" />      <TextView        android:id="@+id/text_view"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/image_view"        android:layout_alignParentTop="true"        android:layout_margin="20dp"        android:layout_toEndOf="@+id/image_view"        android:gravity="center"        android:text="Quick Sort"        android:textColor="@android:color/black"        android:textSize="20sp" />  </RelativeLayout>Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner;  public class AlgorithmItem {    private String algorithmName;      public AlgorithmItem(String countryName)    {        algorithmName = countryName;    }      public String getAlgorithmName()    {        return algorithmName;    }}Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner;  import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList;  public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> {      public AlgorithmAdapter(Context context,                            ArrayList<AlgorithmItem> algorithmList)    {        super(context, 0, algorithmList);    }      @NonNull    @Override    public View getView(int position, @Nullable                                      View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      @Override    public View getDropDownView(int position, @Nullable                                              View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      private View initView(int position, View convertView,                          ViewGroup parent)    {        // It is used to set our custom view.        if (convertView == null) {            convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false);        }          TextView textViewName = convertView.findViewById(R.id.text_view);        AlgorithmItem currentItem = getItem(position);          // It is used the name to the TextView when the        // current item is not null.        if (currentItem != null) {            textViewName.setText(currentItem.getAlgorithmName());        }        return convertView;    }}Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_main.xml      <?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Learn Algorithms"        android:textStyle="bold"        android:textSize="18sp"        android:layout_above="@+id/spinner_algorithm"        android:layout_marginStart="10dp"        android:layout_marginBottom="25dp"        />      <Spinner        android:layout_margin="5dp"        android:id="@+id/spinner_algorithm"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:layout_marginTop="18dp" />  </RelativeLayout>Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner;  import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList;  public class MainActivity extends AppCompatActivity {      ArrayList<AlgorithmItem> algorithmItems;    AlgorithmAdapter adapter;      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          initList();        Spinner spinner = findViewById(R.id.spinner_algorithm);          // we pass our item list and context to our Adapter.        adapter = new AlgorithmAdapter(this, algorithmItems);        spinner.setAdapter(adapter);          spinner.setOnItemSelectedListener(            new AdapterView.OnItemSelectedListener() {                @Override                public void onItemSelected(AdapterView<?> parent,                                           View view, int position, long id)                {                      // It returns the clicked item.                    AlgorithmItem clickedItem = (AlgorithmItem)                                                    parent.getItemAtPosition(position);                    String name = clickedItem.getAlgorithmName();                    Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show();                }                @Override                public void onNothingSelected(AdapterView<?> parent)                {                }            });    }      // It is used to set the algorithm names to our array list.    private void initList()    {        algorithmItems = new ArrayList<>();        algorithmItems.add(new AlgorithmItem("Quick Sort"));        algorithmItems.add(new AlgorithmItem("Merge Sort"));        algorithmItems.add(new AlgorithmItem("Heap Sort"));        algorithmItems.add(new AlgorithmItem("Prims Algorithm"));        algorithmItems.add(new AlgorithmItem("Kruskal Algorithm"));        algorithmItems.add(new AlgorithmItem("Rabin Karp"));        algorithmItems.add(new AlgorithmItem("Binary Search"));    }}
Create a new file algorithm_spinner.xml and add the following code. Each item in spinner will have this layout, an image view and a textview.algorithm_spinner.xmlalgorithm_spinner.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">      <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp"        android:src="@drawable/gfg" />      <TextView        android:id="@+id/text_view"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/image_view"        android:layout_alignParentTop="true"        android:layout_margin="20dp"        android:layout_toEndOf="@+id/image_view"        android:gravity="center"        android:text="Quick Sort"        android:textColor="@android:color/black"        android:textSize="20sp" />  </RelativeLayout>
algorithm_spinner.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">      <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp"        android:src="@drawable/gfg" />      <TextView        android:id="@+id/text_view"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/image_view"        android:layout_alignParentTop="true"        android:layout_margin="20dp"        android:layout_toEndOf="@+id/image_view"        android:gravity="center"        android:text="Quick Sort"        android:textColor="@android:color/black"        android:textSize="20sp" />  </RelativeLayout>
Create a new file AlgorithmItem.java and add the below following code. This is the model class which is used to get the algorithm name when the user clicks on any item. Here we define a constructor and a getAlgorithmName method which returns the algorithm name of the object.AlgorithmItem.javaAlgorithmItem.javapackage org.geeksforgeeks.gfgcustomspinner;  public class AlgorithmItem {    private String algorithmName;      public AlgorithmItem(String countryName)    {        algorithmName = countryName;    }      public String getAlgorithmName()    {        return algorithmName;    }}
AlgorithmItem.java
package org.geeksforgeeks.gfgcustomspinner;  public class AlgorithmItem {    private String algorithmName;      public AlgorithmItem(String countryName)    {        algorithmName = countryName;    }      public String getAlgorithmName()    {        return algorithmName;    }}
Create a new file AlgorithmAdapter.java and add the following code. Here we define our own Adapter class. It maps the item with its view, providing access to the item`s data in the list of spinner.AlgorithmAdapter.javaAlgorithmAdapter.javapackage org.geeksforgeeks.gfgcustomspinner;  import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList;  public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> {      public AlgorithmAdapter(Context context,                            ArrayList<AlgorithmItem> algorithmList)    {        super(context, 0, algorithmList);    }      @NonNull    @Override    public View getView(int position, @Nullable                                      View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      @Override    public View getDropDownView(int position, @Nullable                                              View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      private View initView(int position, View convertView,                          ViewGroup parent)    {        // It is used to set our custom view.        if (convertView == null) {            convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false);        }          TextView textViewName = convertView.findViewById(R.id.text_view);        AlgorithmItem currentItem = getItem(position);          // It is used the name to the TextView when the        // current item is not null.        if (currentItem != null) {            textViewName.setText(currentItem.getAlgorithmName());        }        return convertView;    }}
AlgorithmAdapter.java
package org.geeksforgeeks.gfgcustomspinner;  import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList;  public class AlgorithmAdapter extends ArrayAdapter<AlgorithmItem> {      public AlgorithmAdapter(Context context,                            ArrayList<AlgorithmItem> algorithmList)    {        super(context, 0, algorithmList);    }      @NonNull    @Override    public View getView(int position, @Nullable                                      View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      @Override    public View getDropDownView(int position, @Nullable                                              View convertView, @NonNull ViewGroup parent)    {        return initView(position, convertView, parent);    }      private View initView(int position, View convertView,                          ViewGroup parent)    {        // It is used to set our custom view.        if (convertView == null) {            convertView = LayoutInflater.from(getContext()).inflate(R.layout.algorithm_spinner, parent, false);        }          TextView textViewName = convertView.findViewById(R.id.text_view);        AlgorithmItem currentItem = getItem(position);          // It is used the name to the TextView when the        // current item is not null.        if (currentItem != null) {            textViewName.setText(currentItem.getAlgorithmName());        }        return convertView;    }}
Add the following code in activity_main.xml file. Here we add our spinner on the layout. This will add a textview and a spinner.activity_main.xmlactivity_main.xml      <?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Learn Algorithms"        android:textStyle="bold"        android:textSize="18sp"        android:layout_above="@+id/spinner_algorithm"        android:layout_marginStart="10dp"        android:layout_marginBottom="25dp"        />      <Spinner        android:layout_margin="5dp"        android:id="@+id/spinner_algorithm"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:layout_marginTop="18dp" />  </RelativeLayout>
activity_main.xml
      <?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Learn Algorithms"        android:textStyle="bold"        android:textSize="18sp"        android:layout_above="@+id/spinner_algorithm"        android:layout_marginStart="10dp"        android:layout_marginBottom="25dp"        />      <Spinner        android:layout_margin="5dp"        android:id="@+id/spinner_algorithm"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:layout_marginTop="18dp" />  </RelativeLayout>
Now add the following code in the MainActivity.java file. Here AlgorithmAdapter class object is made and it acts as an adapter for the spinner and add onItemSelectedListner() to our spinner. When the user tap on any item of the spinner, it gets invoked. It shows a toast with the name of the item that user selected from the list.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgcustomspinner;  import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList;  public class MainActivity extends AppCompatActivity {      ArrayList<AlgorithmItem> algorithmItems;    AlgorithmAdapter adapter;      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          initList();        Spinner spinner = findViewById(R.id.spinner_algorithm);          // we pass our item list and context to our Adapter.        adapter = new AlgorithmAdapter(this, algorithmItems);        spinner.setAdapter(adapter);          spinner.setOnItemSelectedListener(            new AdapterView.OnItemSelectedListener() {                @Override                public void onItemSelected(AdapterView<?> parent,                                           View view, int position, long id)                {                      // It returns the clicked item.                    AlgorithmItem clickedItem = (AlgorithmItem)                                                    parent.getItemAtPosition(position);                    String name = clickedItem.getAlgorithmName();                    Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show();                }                @Override                public void onNothingSelected(AdapterView<?> parent)                {                }            });    }      // It is used to set the algorithm names to our array list.    private void initList()    {        algorithmItems = new ArrayList<>();        algorithmItems.add(new AlgorithmItem("Quick Sort"));        algorithmItems.add(new AlgorithmItem("Merge Sort"));        algorithmItems.add(new AlgorithmItem("Heap Sort"));        algorithmItems.add(new AlgorithmItem("Prims Algorithm"));        algorithmItems.add(new AlgorithmItem("Kruskal Algorithm"));        algorithmItems.add(new AlgorithmItem("Rabin Karp"));        algorithmItems.add(new AlgorithmItem("Binary Search"));    }}
MainActivity.java
package org.geeksforgeeks.gfgcustomspinner;  import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList;  public class MainActivity extends AppCompatActivity {      ArrayList<AlgorithmItem> algorithmItems;    AlgorithmAdapter adapter;      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          initList();        Spinner spinner = findViewById(R.id.spinner_algorithm);          // we pass our item list and context to our Adapter.        adapter = new AlgorithmAdapter(this, algorithmItems);        spinner.setAdapter(adapter);          spinner.setOnItemSelectedListener(            new AdapterView.OnItemSelectedListener() {                @Override                public void onItemSelected(AdapterView<?> parent,                                           View view, int position, long id)                {                      // It returns the clicked item.                    AlgorithmItem clickedItem = (AlgorithmItem)                                                    parent.getItemAtPosition(position);                    String name = clickedItem.getAlgorithmName();                    Toast.makeText(MainActivity.this, name + " selected", Toast.LENGTH_SHORT).show();                }                @Override                public void onNothingSelected(AdapterView<?> parent)                {                }            });    }      // It is used to set the algorithm names to our array list.    private void initList()    {        algorithmItems = new ArrayList<>();        algorithmItems.add(new AlgorithmItem("Quick Sort"));        algorithmItems.add(new AlgorithmItem("Merge Sort"));        algorithmItems.add(new AlgorithmItem("Heap Sort"));        algorithmItems.add(new AlgorithmItem("Prims Algorithm"));        algorithmItems.add(new AlgorithmItem("Kruskal Algorithm"));        algorithmItems.add(new AlgorithmItem("Rabin Karp"));        algorithmItems.add(new AlgorithmItem("Binary Search"));    }}
Output:
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Introduction to Java
Constructors in Java