Implement Search functionality in Android Spinner

0
326

Implement Search functionality in Android Spinner | Hello, Developers! Hope you are having a good time learning with mytrendin. You can now click the notification icon to get notified whenever we add any new blog! In this tutorial, we will learn how to make our Android Spinner better! In other words, we will do a simple implementation of Spinner where we will provide it a search functionality to make choosing items easier. For those who haven’t used Android Spinner than you can consider it as a view that has a drop down kind of interface with which you may choose your item. Items are shown in Android Spinner using Adapter. Unlike ListView and GridView, Spinners consumes very less space (appearance wise) in your layout. so choosing options with spinner is a lot easier. But in case you have lots of items like maybe a list of cities, then search functionality could be a very good requirement of yours. we will use a library to do this project. Keep following the blog below to learn how to do this. You may also download the apk and the project from the links given above.

Output: –

Download Project – [media-downloader media_id=”1763″]

Download APK – [media-downloader media_id=”1764″]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

 

Creating New Project  –

Step 1: – Creating Project

Open your Android Studio -> Create a new project -> Choose BlankActivity > Finish

Step 2: Add dependencies in App Level Gradle

Add the dependency in the Gradle.  We are using toptoche library for this implementation

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.1.1'

    compile 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
}

Step 3: Making Layout activity_main.xml

this file is responsible for how your code will look like. you can either integrate this Spinner in a form or as if required. We are doing a basic implementation so we have kept the code minimalistic for your better understanding.

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:background="#4DB567">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_margin="20dp">

        <com.toptoche.searchablespinnerlibrary.SearchableSpinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Choose From Options"
            android:padding="5dp"
            android:textStyle="bold"/>
    </LinearLayout>


</RelativeLayout>

Related:

How to set Adapter to Spinner Dynamically

Search an element in a given Singly Linked list.

Receive SMS in Application and Search for keywords

Android Custom ListView using BaseAdapter

Linked List Introduction

Step 4: Add items for Spinner in strings.xml

We will fetch this string-array using our adapter.

<resources>
    <string name="app_name">SpinnerSearch</string>

    <string-array name="symptoms">
        <item>Choose your Problems</item>
        <item>Common Fever</item>
        <item>Dark Circles</item>
        <item>Obesity</item>
        <item>Stress</item>
        <item>Wrinkles</item>
    </string-array>
</resources>

Step 5: Creating MainActivity.java

Provide the layout to your app

setContentView(R.layout.activity_main);

Now we will locate Spinner in our layout

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

Now to populate the items in our Spinner or to add data to Spinner, we will use an ArraryAdapter.

   ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.symptoms, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

As you can see here we have provided the “symptoms” array as the list of items for our Spinner. This array is to be made in the strings.xml file. we will have to Execute some code when any item of our Android Spinner will be clicked. Therefore we use

  spinner.setOnItemSelectedListener(this);

We use onClickListener for Buttons, but in the case of Spinner, we use OnItemSelectedListener as it contains a list of items and code has to be executed on the basis of items which has been chosen by the user.

Your entire MainActivity.java will look like this:

package com.mytrendin.spinnersearch;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.symptoms, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String selectedItem = parent.getItemAtPosition(position).toString();
        switch (selectedItem) {
            case "Select one Item":
                break;
            case "Common Fever":
                Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
                break;
            case "Dark Circles":
                Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
                break;
            case "Obesity":
                Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
                break;
            case "Stress":
                Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
                break;
            case "Wrinkles":
                Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

Now you may execute the code and observe the changes. In the case of any queries comment below. We love comments. Thank you! If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here