Android Material Spinner

A spinner is an android widget that basically displays items in dropdown. Thus allowing ussers to select only one item at a time.

The parent class of the inbuilt android spinner is the AbsSpinner, a an abstract adapterview.

However, sometimes we are not so much attracted to the inbuilt or default spinner, due to functionality limitations or we just want something nicer.

In that case we can look at GitHub and obtain a third party library.

Material Spinner is such library. It was first created by Jared Rumler more than 2 years ago. Since then it’s been receiving updates.

===

This library provides us an awesome spinner view for android.

MaterialSpinner Definition

MaterialSpinner is not built from the Spinner widget provided by android. Instead it’s a custom Spinner built from TextView.

First it belongs to the following package:

package com.jaredrummler.materialspinner;

It’s a public class deriving from TextView:

public class MaterialSpinner extends TextView {}

Creating Material Spinner

MaterialSpinner provides three public contructors for programmatic creation:

No. Contsructor
1. public MaterialSpinner(Context context) {}
2. public MaterialSpinner(Context context, AttributeSet attrs) {}
3. public MaterialSpinner(Context context, AttributeSet attrs, int defStyleAttr) {}

Internally, these contructors call a method called init() where they pass their parameters to that method. It is the init() method which then retrieves the default properties to be used from the resources. These properties include

  • TextColor
  • BackgroundColor
  • HintColor
  • PopupWindow Height dimensions etc

Furthermore a ListView gets instantiated inside this init() method among other things. It is this ListView that will be used to render the dropdown list of items.

Creation Via XML

You can also set the MaterialSpinner via XML layout:

<com.jaredrummler.materialspinner.MaterialSpinner
    android_id="@+id/spinner"
    android_layout_width="match_parent"
    android_layout_height="wrap_content"/>

then reference it from the Code:

MaterialSpinner mySpinner = (MaterialSpinner) findViewById(R.id.spinner);

Populating the MaterialSpinner

MaterialSpinner, even though it derives from TextView, is a spinner, a custom one.
Hence it renders collection of items in a dropdown list.

Normally with the default android spinner, you create an adapter explicitly to bind to your adapter.

However, MaterialSpinner is easier to use and saves you from this.

It internally maintains an adapter for you, a custom adapter called MaterialSpinnerAdapter.

That adapter is a child of BaseAdapter.

MaterialSpinner provides us with a public method called setItems() which we overload with different parameter types.

No. Method Description
1. public void setItems(@NonNull T… items) Internally it calls the other setItems() method converting our passed array to a list and passing it as a parameter
2. public void setItems(@NonNull List items) Passes this List to a MaterialSpinnerAdapter constructor. Then sets the adapter instance internally to the MaterialSpinner.
Usage Example

Here’s an example:

mySpinner.setItems("Casini", "Galileo", "James Web", "Hubble", "Chandra");

Note you haven’t set any adapter explicitly.

Via Adapter

You can also use an adapter.

This can be a custom adapter by passing in a ListAdapter reference:

 public void setAdapter(@NonNull ListAdapter adapter) {}

This will instantiate a MaterialSpinnerAdapterWrapper class, passing in your ListAdapter object. Then moving the MaterialSpinnerAdapterWrapper instance into setAdapterInternal private method.

Or by passing a MaterialSpinnerAdapter instance into the setAdapter() method:

 public <T> void setAdapter(MaterialSpinnerAdapter<T> adapter) {}

This will also pass that adapter into the setAdapterInternal() method.
The setAdapterInternal() is a private method residing in the MaterialSpinner class with the following responsibilities:

  1. Set the the MaterialSpinnerAdapter instance it receieves as the adapter for our ListView. Note that the MaterialSpinnerAdapter itself is a child of BaseAdapter, so ListView can accept it.
  2. Check if the passed adapter has items in it. Then set the hint text, hint color and text color.

Listening To Selection Change Events

We can listen to selection change events for our spinner in a very easy manner:

mySpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

  @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
    Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
  }
});

Installing MaterialSpinner

This library can be installed in three ways depending on your build system and preferences:

  1. Direct download of the Android Archive file.
  2. Grabbing via Gradle:
    compile 'com.jaredrummler:material-spinner:1.2.5'
  3. Grab via Maven:
    <dependency>
    <groupId>com.jaredrummler</groupId>
    <artifactId>material-spinner</artifactId>
    <version>1.2.5</version>
    <type>aar</type>
    </dependency>

Material Spinner Example

Let’s now look at a material spinner example.

Questions this Example Answers
  1. Android Material Spinner Library and example.
  2. How to populate material spinner with an array of data.
  3. How to listen to selection events of material spinner.
Gradle Scripts
(a)Build.gradle

First we need to install Material Spinner by adding the following implementation statement in our app level build.gradle:

implementation 'com.jaredrummler:material-spinner:1.2.5'
Resources

We will have two XML Layouts:

(a). activity_main.xml

Here’s our activity_main.xml. At the root we have a CoordinatorLayout.

Take note we are including the content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_fitsSystemWindows="true"
    tools_context=".MainActivity">

  <android.support.design.widget.AppBarLayout
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android_id="@+id/toolbar"
        android_layout_width="match_parent"
        android_layout_height="?attr/actionBarSize"
        android_background="?attr/colorPrimary"
        app_popupTheme="@style/AppTheme.PopupOverlay"/>

  </android.support.design.widget.AppBarLayout>

  <include layout="@layout/content_main"/>

  <android.support.design.widget.FloatingActionButton
      android_id="@+id/fab"
      android_layout_width="wrap_content"
      android_layout_height="wrap_content"
      android_layout_gravity="bottom|end"
      android_layout_margin="@dimen/fab_margin"
      android_src="@drawable/ic_github_white_24dp"/>

</android.support.design.widget.CoordinatorLayout>
(b) content_main.xml

This is where we add our MaterialSpinner. At the root we have a RelativeLayout.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context=".MainActivity"
    tools_showIn="@layout/activity_main">

  <com.jaredrummler.materialspinner.MaterialSpinner
      android_id="@+id/spinner"
      app_ms_dropdown_max_height="350dp"
      app_ms_dropdown_height="wrap_content"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"/>

</RelativeLayout>

Java Code

(a). MainActivity.java

This is our launcher and only activity. We will populate our MaterialSpinner with an array of strings.

First we are referencing our material spinner from our layout using findViewById() method of the Activity class:

    MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);

To fill our materialspinner with data we simply use the setItems() method:

    spinner.setItems(ANDROID_VERSIONS);

Then we also listen to the item selection events our Spinner:

    spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

      @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
        Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
      }
    });
    spinner.setOnNothingSelectedListener(new MaterialSpinner.OnNothingSelectedListener() {

      @Override public void onNothingSelected(MaterialSpinner spinner) {
        Snackbar.make(spinner, "Nothing selected", Snackbar.LENGTH_LONG).show();
      }
    });

Here’s the full code:

package com.jaredrummler.materialspinner.example;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.jaredrummler.materialspinner.MaterialSpinner;

public class MainActivity extends AppCompatActivity {

  private static final String[] ANDROID_VERSIONS = {
      "Cupcake",
      "Donut",
      "Eclair",
      "Froyo",
      "Gingerbread",
      "Honeycomb",
      "Ice Cream Sandwich",
      "Jelly Bean",
      "KitKat",
      "Lollipop",
      "Marshmallow",
      "Nougat",
      "Oreo"
  };

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View view) {
        try {
          startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/jaredrummler/MaterialSpinner")));
        } catch (ActivityNotFoundException ignored) {
        }
      }
    });

    MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);
    spinner.setItems(ANDROID_VERSIONS);
    spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

      @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
        Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
      }
    });
    spinner.setOnNothingSelectedListener(new MaterialSpinner.OnNothingSelectedListener() {

      @Override public void onNothingSelected(MaterialSpinner spinner) {
        Snackbar.make(spinner, "Nothing selected", Snackbar.LENGTH_LONG).show();
      }
    });
  }

}

Download

Also check our video tutorial it’s more detailed and explained in step by step.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse

Credit to the Original Creator Jared Rumler

Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )