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.
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:
- RelativeLayout – Our root element.
- TextView – To render our header text.
- Spinner – Our dropdown widget. We’ll use it to filter our listview.
- ListView – Our adapterview. Will render our list of items.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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 |
Hello
How do I get the information to be displayed in a personalized ListView?
I’ve tried it a few times, but to no avail.
Taking the opportunity, in this same code is it possible to use two Spinners to filter? If so, can you give me an example?
Thank you in advance!