Adv

Android Spinner

Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.

Spinner is an AdapterView. This means that it relies on an Adapter for its data.

Adapters act as the bridge between adapterviews and the underlying data source.

This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.

Spinner is a concrete public class residing in the android.widget package.

package android.widget;

Spinner is a public class that’s why we can access and use it.

public class
Spinner{}

Public classes are visible even from other packages apart from those they’ve been defined.

Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.

AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.

AbsSpinner

AbsSpinner is the parent class for Spinner.

Spinner is a view that allows us display items in a dropdown manner, allowing user pick a single item at a time.

Spinner relies on abstractions defined in this AbsSpinner class, inheriting several concrete and abstract methods.

The fact that this class has abstract methods means it’s also abstract.

public abstract class AbsSpinner...{}

This class is an adapterview. So it’s children will rely on an Adapter for binding of data. Specifically a SpinnerAdapter.
public abstract class AbsSpinner extends AdapterView<SpinnerAdapter>

This class like other adapterviews is defined in the android.widget package. It’s existed since the first release of Android, API Level 1.

You won’t use this class in your day to day projects since it’s a base class meant to provide abstraction to the Spinner class. Instead you’ll use Spinner.

This class has 3 children:

Subclass Description
Spinner view used to provide a quick way to select a single value from a set.
Gallery view that shows items in a center-locked, horizontally scrolling list.DEPRECATED IN API LEVEL 16.

 

===

Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.

Spinner is an AdapterView. This means that it relies on an Adapter for its data.

Adapters act as the bridge between adapterviews and the underlying data source.

This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.

Spinner is a concrete public class residing in the android.widget package.

package android.widget;

Spinner is a public class that’s why we can access and use it.

public class Spinner{}

Public classes are visible even from other packages apart from those they’ve been defined.

Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.

AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.

How to Define Spinner in Layout

We can use the Spinner object to specify the spinner in an xml Layout. This pattern of specifyng an Object in the Layout resource then referencing from the Java/Kotlin code is common in android as a platform and is also the one recommended.

Here are some of it’s advantages:

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generation tools to generate XML as an alternative to Android Studio.
<Spinner
    android_id="@+id/mySpinner"
    android_layout_width="fill_parent"
    android_layout_height="wrap_content" />

 

How to Populate Spinner

Then in our java code we can first reference the Spinner from our Layout specification using the findViewById() method our activity class.

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

We can then instantiate a SpinnerAdapter(e.g ArrayAdapter). We use the default spinner Layout(android.R.layout.simple_spinner_item).

We are using a static method called createFromResource(). This method is provided by the ArrayAdapter class and it returns us an ArrayAdapter instance from the external resource we provide it as our data source.

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.galaxies_array, android.R.layout.simple_spinner_item);

You have to make sure you’ve added string array into your strings.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="galaxies_array">
        <item>Milky Way</item>
        <item>Andromeda</item>
        <item>Whirlpool</item>
        <item>Sombrero</item>
        <item>Cartwheel</item>
        <item>StarBust</item>
        <item>Pinwheel</item>
        <item>Leo</item>
    </string-array>
</resources>

ArrayAdapter provides us the createFromResource() method which gives us an instance of the ArrayAdapter from the string array we provided.

After that:

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

This method allows us specify the Layout the adapter will use to display the list of spinner choices. We use the one provided by the Android Platform.

Finally we set the adapter:

spinner.setAdapter(adapter);

 

 

Share

Related Concepts

Adv

2 Examples

  1. Android Spinner with CardViews with Images and text tutorial

    Android Spinner with CardViews with Images and text tutorial.

    In this tutorial we’ll look at a custom Spinner with cardviews. The cardviews will have both images and text. We’ll also see how to handle the selected item click listener for our Spinner.

    We will have three classes:

    1. Spacecraft – Model class.
    2. CustomAdapter – A custom spinner adapter.
    3. MainActivity – The main activity.

    Tools Used

    This example was written with the following tools:

    • Windows 8
    • AndroidStudio IDE
    • Genymotion Emulator
    • Language : Java

    (a). Spacecraft.java

     

    package com.tutorials.hp.spinnerimgtext;
    
    /**
     * Created by Oclemy on 8/4/2016 for ProgrammingWizards Channel and http://www.camposha.com.
     */
    public class Spacecraft {
    
        String name,propellant;
        int image;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getImage() {
            return image;
        }
    
        public void setImage(int image) {
            this.image = image;
        }
    
        public void setPropellant(String propellant) {
            this.propellant = propellant;
        }
    
        public String getPropellant() {
            return propellant;
        }
    }

     

     

    (b). CustomAdapter.java

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    
    /**
     * Created by Oclemy on 8/4/2016 for ProgrammingWizards Channel and http://www.camposha.com.
     */
    public class CustomAdapter extends BaseAdapter {
    
        Context c;
        ArrayList<Spacecraft> spacecrafts;
    
        public CustomAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
            this.c = c;
            this.spacecrafts = spacecrafts;
        }
    
        @Override
        public int getCount() {
            return spacecrafts.size();
        }
    
        @Override
        public Object getItem(int i) {
            return spacecrafts.get(i);
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
    
            if(view==null)
            {
                view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
            }
    
            final Spacecraft s= (Spacecraft) this.getItem(i);
    
            TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
            TextView propTxt= (TextView) view.findViewById(R.id.propellantTxt);
            ImageView img= (ImageView) view.findViewById(R.id.spacecraftImg);
    
            nameTxt.setText(s.getName());
            propTxt.setText(s.getPropellant());
            img.setImageResource(s.getImage());
    
            return view;
        }
    }

     

    (c). MainActivity.java

    The main activity.

     

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Spinner;
    import android.widget.SpinnerAdapter;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        ArrayList<Spacecraft> spacecrafts;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Spinner sp= (Spinner) findViewById(R.id.sp);
            getData();
            sp.setAdapter(new CustomAdapter(this,spacecrafts));
    
            sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    Toast.makeText(MainActivity.this, spacecrafts.get(i).getName(), Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {
    
                }
            });
    
    
    
        }
    
        private ArrayList getData()
        {
            spacecrafts=new ArrayList<>();
    
            Spacecraft s=new Spacecraft();
            s.setName("Pioneer");
            s.setPropellant("Chemical Energy");
            s.setImage(R.drawable.pioneer);
            spacecrafts.add(s);
    
            s=new Spacecraft();
            s.setName("Spitzer");
            s.setPropellant("Warp Drive");
            s.setImage(R.drawable.spitzer);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Enterprise");
            s.setPropellant("Anti Matter");
            s.setImage(R.drawable.enterprise);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Hubble");
            s.setPropellant("Laser Beam");
            s.setImage(R.drawable.hubble);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Voyager");
            s.setPropellant("Solar Energy");
            s.setImage(R.drawable.voyager);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Kepler");
            s.setPropellant("Solar Energy");
            s.setImage(R.drawable.kepler);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Rosetter");
            s.setPropellant("Nuclear Energy");
            s.setImage(R.drawable.rosetta);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("WMAP");
            s.setPropellant("Nuclear Energy");
            s.setImage(R.drawable.wmap);
            spacecrafts.add(s);
    
    
            s=new Spacecraft();
            s.setName("Columbia");
            s.setPropellant("Chemical Energy");
            s.setImage(R.drawable.columbia);
            spacecrafts.add(s);
    
            return spacecrafts;
        }
    
    
    }

     

    Download

    Download Full Code here.

     

  2. Adv
  3. Android Simple Spinner and OnItemSelected

    Hello friends.We have a look at android simple Spinner and see how to load data from a simple arraylist with help of arrayadapter.We also see how to handle ItemSelected events.

     

    Here’s the demo :

    Project Demo

    API Reference – Important APIs to Know First

    Here are the API’s we’ve used for this project.

    (a). Spinner – a DropDown Widget

    <!–
    {{ page.find(‘/android/spinner’).contentMeta.shortcodeMeta.shortcode.section.android_spinner_intro }}
    –>
    <!– **1. How to Define Spinner within XML**
    {{ page.find(‘/android/spinner’).contentMeta.shortcodeMeta.shortcode.section.android_define_spinner }}
    –>

    2. How to Import Spinner
    We use the import keyword:

    import android.widget.Spinner;

    2. How to Reference Spinner
    We reference spinner using the findViewById() method.

            Spinner sp= (Spinner) findViewById(R.id.sp);
    (b). ArrayList – a collection

    <!– **1. What is an ArrayList?**
    {{ page.find(‘/java/arraylist’).contentMeta.shortcodeMeta.shortcode.section.java_arraylist_intro }}
    –>

    2. How to Instantiate an ArrayList

    Here’s how, we use the new keyword:

        ArrayList<String> languages=new ArrayList<>();

    3. How to add items to an ArrayList
    We use the add() method. First we are clearing it to avoid duplicates.

            languages.clear();
    
            //FILL
            languages.add("Java");
            languages.add("C#");
            languages.add("VB.NET");
            languages.add("PHP");
            ....

     MainActivity.java

    • Our MainActivity
    package com.tutorials.hp.simplespinner;
    
    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;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
        ArrayList<String> languages=new ArrayList<>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //SPINNER
            Spinner sp= (Spinner) findViewById(R.id.sp);
    
            //FILL DATA
            fillData();
    
            //ADAPTR
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,languages);
            sp.setAdapter(adapter);
    
            sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    Toast.makeText(MainActivity.this, languages.get(i), Toast.LENGTH_SHORT).show();
    
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {
    
                }
            });
        }
    
        //FILL DATA
        private void fillData()
        {
            languages.clear();
    
            //FILL
            languages.add("Java");
            languages.add("C#");
            languages.add("VB.NET");
            languages.add("PHP");
            languages.add("Python");
            languages.add("Ruby");
            languages.add("C");
            languages.add("C++");
            languages.add("Fortran");
            languages.add("Cobol");
            languages.add("Perl");
            languages.add("Prolog");
        }
    }
    

    SECTION 2 : Our Layout*

    <?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"
        tools_context="com.tutorials.hp.simplespinner.MainActivity">
    
        <Spinner
            android_id="@+id/sp"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            />
    </RelativeLayout>
    

    SOURCE CODE REFERENCE




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )