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

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

Android Spinner

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.

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" />

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

An ArrayList is a Resizable-array implementation of the List interface.

This class is one of the most commonly used collection in the java environment. It's so flexible and easy to use and powerful. It's power and flexibility come from the fact that ArrayList implements all optional list operations, and permits all elements, including null.

Internally an ArrayList utilizes an Array to store it's items. Because of this some developers usually refer to an ArrayList as a dynamic array.

Hence the ArrayList class provides methods to manipulate the size of the array that is used internally to store the list.

The ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

While using an ArrayList keep the following in mind for the sake of performance:

  1. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  2. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  3. All of the other operations run in linear time (roughly speaking).
  4. The constant factor is low compared to that for the LinkedList implementation.

When you instantiate an ArrayList, you get access to the ArrayList capacity for that instance. This capacity is the size of the array used to store the elements in the list. The ArrayList is always at least as large as the list size.

Then as you add more elements to an ArrayList, its capacity grows automatically. Adding an element to an ArrayList has constant amortized time cost.

You can increases your ArrayList capacity using the ensureCapacity operation. This may reduce the amount of incremental reallocation and can be useful before adding a large number of elements.

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 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"
    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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post