Android Filter ListView using a Spinner/Dropdown

| Page Views: 2473

Android Filter ListView using Spinner Example

In this class we will see how to filter a ListView component in android using a spinner.

A spinner is a widget that allows us render items in a dropdown. This type of app is useful if you want to filter items using a give category.

Demo

Here are demo images for this tutorial.

Android ListView Filter using Spinner

Android ListView Filter using Spinner

Video Tutorial(Recommended)

Here's the video tutorial. I recommend you watch the video tutorial as it contains explantions on step by step process of how to create this. We start from scratch by creating a project and I take you through all the steps and code.

Layouts

(a). activity_main.xml

This is the main activity layout. Here we have the following widgets and layouts:

  1. RelativeLayout - Our root element.
  2. TextView - To render our header text.
  3. Spinner - Our dropdown widget. We'll use it to filter our listview.
  4. ListView - Our adapterview. Will render our list of items.
<?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="info.camposha.listviewdropdownspinner.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="Cosmic Bodies"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_below="@id/headerLabel"
        android:layout_centerHorizontal="true"
        android:background="@android:drawable/editbox_dropdown_light_frame" />
    <ListView
        android:id="@+id/myListView"
        android:layout_below="@id/mySpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Java Code

We have only class.

(a). MainActivity.java

This is our main activity. It's deriving from the activity class. We'll use an ArrayAdapter to bind our data to our ListView. We'll also have a string array to contain our categories.

package info.camposha.listviewdropdownspinner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {

    ListView myListView;
    Spinner mySpinner;
    ArrayAdapter<CosmicBody> adapter;
    String[] categories={"All","Planets","Stars","Galaxies"};
    /*
    when activity is created, setContentView then initializeViews.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initializeViews();
    }
    /*
    Initialize ListView and Spinner, set their adapters and listen to spinner itemSelection events
    */
    private void initializeViews() {

        mySpinner = findViewById(R.id.mySpinner);
        mySpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, categories));

        myListView = findViewById(R.id.myListView);
        myListView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies()));

        //spinner selection events
        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long itemID) {
                if (position >= 0 && position < categories.length) {
                    getSelectedCategoryData(position);
                } else {
                    Toast.makeText(MainActivity.this, "Selected Category Does not Exist!", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    /*
    Populate an arraylist that will act as our data source.
     */
    private ArrayList<CosmicBody> getCosmicBodies() {
        ArrayList<CosmicBody> data = new ArrayList<>();
        data.clear();

        data.add(new CosmicBody("Mercury", 1));
        data.add(new CosmicBody("UY Scuti", 1));
        data.add(new CosmicBody("Andromeda", 3));
        data.add(new CosmicBody("VV Cephei A", 2));
        data.add(new CosmicBody("IC 1011", 3));
        data.add(new CosmicBody("Sun", 2));
        data.add(new CosmicBody("Aldebaran", 2));
        data.add(new CosmicBody("Venus", 1));
        data.add(new CosmicBody("Malin 1", 3));
        data.add(new CosmicBody("Rigel", 2));
        data.add(new CosmicBody("Earth", 1));
        data.add(new CosmicBody("Whirlpool", 3));
        data.add(new CosmicBody("VY Canis Majoris", 2));
        data.add(new CosmicBody("Saturn", 1));
        data.add(new CosmicBody("Sombrero", 3));
        data.add(new CosmicBody("Betelgeuse", 2));
        data.add(new CosmicBody("Uranus", 1));
        data.add(new CosmicBody("Virgo Stellar Stream", 3));
        data.add(new CosmicBody("Epsillon Canis Majoris", 2));
        data.add(new CosmicBody("Jupiter", 1));
        data.add(new CosmicBody("VY Canis Majos", 2));
        data.add(new CosmicBody("Triangulum", 3));
        data.add(new CosmicBody("Cartwheel", 3));
        data.add(new CosmicBody("Antares", 2));
        data.add(new CosmicBody("Mayall's Object", 3));
        data.add(new CosmicBody("Proxima Centauri", 2));
        data.add(new CosmicBody("Black Eye", 3));
        data.add(new CosmicBody("Mars", 1));
        data.add(new CosmicBody("Sirius", 2));
        data.add(new CosmicBody("Centaurus A", 3));
        data.add(new CosmicBody("Pinwheel", 3));
        data.add(new CosmicBody("Small Magellonic Cloud", 3));
        data.add(new CosmicBody("Uranus", 1));
        data.add(new CosmicBody("Alpha Centauri", 2));
        data.add(new CosmicBody("Large Magellonic Cloud", 3));

        return data;
    }
    /*
    Get the selected category's cosmic bodies and bind to ListView
     */
    private void getSelectedCategoryData(int categoryID) {
        //arraylist to hold selected cosmic bodies
        ArrayList<CosmicBody> cosmicBodies = new ArrayList<>();
        if(categoryID == 0)
        {
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getCosmicBodies());
        }else{
            //filter by id
            for (CosmicBody cosmicBody : getCosmicBodies()) {
                if (cosmicBody.getCategoryId() == categoryID) {
                    cosmicBodies.add(cosmicBody);
                }
            }
            //instatiate adapter a
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, cosmicBodies);
        }
        //set the adapter to GridView
        myListView.setAdapter(adapter);
    }
}
/*
Data Object class to represent a single Cosmic body. Class has default access modifier
 */
class CosmicBody {
    private String name;
    private int categoryID;

    public String getName() {
        return name;
    }

    public int getCategoryId() {
        return categoryID;
    }

    public CosmicBody(String name, int categoryID) {
        this.name = name;
        this.categoryID = categoryID;
    }

    @Override
    public String toString() {
        return name;
    }
}
Download

You can download the full source code below or watch the video from the link provided.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube ProgrammingWizards TV Channel
5. Camposha GridView version

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.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post