Android Spinner Searchable With Search Box Example

android custom spinner with image, Android Custom Spinner Dropdown arrow background, android spinner search hint prompt text, android spinner divider, android spinner text color size. android spinner searchable, android spinner disable item dropdown, android spinner custom adapter

We will make two examples of Android Spinner Searchable in this post.

Table of Content

1. Android Spinner Searchable With Search Box Example

2. Android Spinner Search Hint Prompt Text And Background Color





1. Android Spinner Searchable With Search Box Example

Learn to create Android Spinner Searchable With Search Box Example.

In this article, we will create filterable drop down of spinner in android studio.

We can put a search box at the top of the spinner drop down to filter the options.

This feature gives us the same result as we get from the searchview.

Android’s in-built system do not give us chance to put searchview in the spinner in any way.

You may find any library on github regarding using searchview in spinner the you can use them easily.

In today’s article, I will use github library but it is not using searchview.

We just need to use the desired XML version of spinner in layout file.

Rest of the things are very easy and smooth.

Ending View

Step 1. Defining Dependencies

I am going to use this github library in this example.

So add the following line in your build.gradle(Module:app) file

 implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
  • Above line will download all the required classes from repository.
  • Then we can use this library’s sentences easily.

Step 2. Layout

Add the following coding lines in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <com.toptoche.searchablespinnerlibrary.SearchableSpinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        />

</android.support.constraint.ConstraintLayout>

As you can see that I have taken <com.toptoche…..> instead of classical <spinner> tag.

This new tag will implement a spinner from the github library.

So this spinner will react according to the classes written in the library instead of traditional spinner.

Step 3. Adding Options

Generally, we define spinner options name in string array variable. We also define this variable in java class only.

But in current scenario, we will add spinner options in strings.xml file.

strings.xml file is created automatically in every android studio project.

You can find this file under res->values directory.

Add the below code lines in strings.xml file.

 <string-array name="Animals">
        <item>Select Animal!!</item>
        <item>Lion</item>
        <item>Tiger</item>
        <item>Elephant</item>
        <item>Zebra</item>
        <item>Giraffe</item>
        <item>Deer</item>
    </string-array>

Traditionally, we create string array in java files but in this case we have define it as above.

We will use this variable “Animals”, in the JAVA file to populate the spinner.

Step 4. Final Change

Let us make a last change to make searchable spinner.

Write down the below coding lines in MainActivity.java file

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;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    String[] options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        // Creating ArrayAdapter using the string array and default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.Animals, android.R.layout.simple_spinner_item);
        // Specify layout to be used when list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Applying the adapter to our spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

        options = MainActivity.this.getResources().getStringArray(R.array.Animals);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(this, " You select >> "+options[position], Toast.LENGTH_SHORT).show();

    }

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

    }
}

Moving Deep in Above code

Below line is creating a string array variable.

String[] options;
  • I have written this line before the onCreate() method, so that we can use this variable (options) through out the whole class.

Now consider the below source code

 Spinner spinner = (Spinner) findViewById(R.id.spinner);
        // Creating ArrayAdapter using the string array and default spinner layout
 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.Animals, android.R.layout.simple_spinner_item);

First line is finding the spinner with use of it’s ID from the activity_main.xml file

Second line is creating an object of the ArrayAdapter class.

This object will get the strings from the string array variable (Animals) of the strings.xml file

simple_spinner_item from the above code is in-built file to represent the front view of the spinner.

Read the below coding lines

// Specify layout to be used when list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Above line will specify a file to be used to generate a view of drop down.

simple_spinner_dropdown_item is also a system generated file of android structure.

Let us understand the below lines

 // Applying the adapter to our spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

These lines will first set the adapter to our spinner.

Then compiler will set the onItemSelected Listener for the spinner.

Following line will generate string array from the strings.xml file

options = MainActivity.this.getResources().getStringArray(R.array.Animals);

Now we can use the options variable anywhere in the class as a string array.

It contains all the spinner options in string format.

When the user selects the option from the spinner, compiler will call the below method.

 @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(this, " You select >> "+options[position], Toast.LENGTH_SHORT).show();

    }

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

    }

When user have selects a specific options then compiler will call onItemSelected() method.

If user do not choose any option then compiler will call onNothingSelected() method.

onItemSelected() method will simply show a toast that will say that which value is selected by the user.

Thus, we have make android searchable spinner with very little coding lines.

That is the only purpose of DemoNuts to create quality apps with efficient and time saving code structure.





2. Android Spinner Search Hint Prompt Text And Background Color

Android Spinner Search Hint Prompt Text And Background Color Example is for you.

You will learn to set prompt programmatically and to change prompt text and background color.

In android app, developer uses spinner to ask user to select any one choice from drop down menu or pop up dialog.

Here, you may want to give some hint or information to the user about your spinner options.

For example, if your spinner contains fruits as an options. Here, you can use some text like “Select Fruit” as a search hint.

Setting a search hint or prompt text in android spinner is not a tough task.

But customizing them like changing text color, changing background color need little tricks.

We will use two methods to implement search hint.

First by creating a drop down menu and second by using prompt dialog.

Last Look

Implementing Drop Down

Step 1. Add Code in Default Activity

First of all, make a new project in the android studio.

Choose “Empty Activity” after you have given project name and SDK version.

Add the below source code in activity_main.xml

  <Spinner
        android:id="@+id/spFruits"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dropdown"/>

I have taken one spinner in main layout file.

Set the spinner mode as a dropdown or just don’t write this line.

By default, system will create drop down spinner only.

Write down the following coding lines in MainActivity.java file

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;

public class MainActivity extends AppCompatActivity {

    boolean first = true;

    private String[] fruits = {"Select One Fruit","Mango","Orange","Strawberry"};
    private Spinner spFruit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spFruit = findViewById(R.id.spFruits);
        spFruit.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, fruits));
        spFruit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(first){
                    first = false;
                }else {

                    if (position == 0) {
                        Toast.makeText(MainActivity.this, "Please select appropriate option!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, fruits[position] + " Selected !", Toast.LENGTH_SHORT).show();
                    }
                }
            }

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

            }

        });

    }
}

Consider the below code snippet

 boolean first = true;

    private String[] fruits = {"Select One Fruit","Mango","Orange","Strawberry"};
    private Spinner spFruit;

First line is creating a boolean variable. By default it has true value.

Then, I have make one string array which contains the names of the fruits.

In this string array, set your search hint at the first position.

Look at the following code

 spFruit = findViewById(R.id.spFruits);
        spFruit.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, fruits));
        spFruit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(first){
                    first = false;
                }else {

                    if (position == 0) {
                        Toast.makeText(MainActivity.this, "Please select appropriate option!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, fruits[position] + " Selected !", Toast.LENGTH_SHORT).show();
                    }
                }
            }

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

            }

        });

Now above code will first set the adapter to the spinner.

I have also implemented onItemSelectedListener for this spinner. Here, we will use that boolean variable (first).

When the app is loaded for the first time on device, this compiler call this onItemSelectedListener. So it shows toast everytime when app is opened for fist time.

This case is not ideal for user experience or user satisfaction.

So that, boolean variable (first) will help us to overcome this problem.

Making Prompt Search Hint

Step 1. Write XML code

Add the following code in activity_main.xml

 <Spinner
        android:id="@+id/spCars"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"
        android:prompt="@string/app_name"/>

    <Spinner
        android:id="@+id/spCountry"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

   <Spinner
        android:id="@+id/spVehicles"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:paddingLeft="10dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

So the final code for activity_main.xml is something like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Spinner
        android:id="@+id/spCars"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"
        android:prompt="@string/app_name"/>

    <Spinner
        android:id="@+id/spCountry"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

    <Spinner
        android:id="@+id/spFruits"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dropdown"/>

    <Spinner
        android:id="@+id/spVehicles"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:paddingLeft="10dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

</LinearLayout>

Here, I have taken three spinners to give them prompt text.

All these spinners must have the following line

android:spinnerMode="dialog"

Now you can add prompt text using two methods.

  1. Directly add your text in strings.xml and use that string in activity_main.xml
  2. Add ans set the prompt text programmatically in spinner.

Add text using strings.xml

Write the below line in res->values->strings.xml file

 <string name="prompt">Spinner Prompt!!!</string>

Following snippet from activity_main.xml file using this text reference

 <Spinner
        android:id="@+id/spCars"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"
        android:prompt="@string/app_name"/>

Now add the below code in MainActivity.java

 private String[] cars = {"Ferrari","Lamborghini","Rolls Roys"};
 private Spinner spCars;

Write Above code before onCreate() method and write below code inside the onCreate() method

 spCars = findViewById(R.id.spCars);
 spCars.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, cars));

Add Prompt text programmatically

Add the spinner in the activity_main.xml

 <Spinner
        android:id="@+id/spCountry"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

Now add the following in MAinActivity.java

private String[] country = {"India","USA","Canada"};
private Spinner spCountry;

Write above code above the onCreate() method and below inside onCreate()

 spCountry = findViewById(R.id.spCountry);
 spCountry.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, country));
 spCountry.setPrompt("Spinner Prompt Programatically!!!");

Changing Prompt Text And Background Color

Below code from activity_main.xml will get prompt text programmatically.

 <Spinner
        android:id="@+id/spVehicles"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:paddingLeft="10dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dialog"/>

Now we will learn how to change the color of prompt text and background.

For this, we need to create a custom adapter and some layout files.

We will create separate layout files for prompt text and drop down items (spinner options).

So create a new xml layout file under res->layout directory

Give it a name like “vehicle_spinner.xml”

Code for “vehicle_spinner.xml” is as the following

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:id="@+id/spinner_text"
        android:singleLine="true"
        android:layout_marginLeft="50dp"
        android:text="At res"
        android:textColor="#000"
        android:textSize="20sp"
        android:gravity="center_vertical" />


</LinearLayout>

This file will create the layout interface for main spinner’s main or first look.

Create another layout file under same directory named “vehicle_prompt.xml”

Write the below lines in it

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#c10cea"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:id="@+id/vehicle_prompt"
        android:singleLine="true"
        android:layout_marginLeft="50dp"
        android:text="At res"
        android:textColor="#1fedea"
        android:textSize="25sp"
        android:gravity="center_vertical" />


</LinearLayout>

This file will generate the view structure for the prompt text.

You can change the prompt text size, color, padding, margin etc. in this file.

Make another layout file with the name vehicle_dropdown.xml

Source code for vehicle_dropdown.xml is as the following

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/vehicle_dropdown"
        android:layout_width="match_parent"
        android:gravity="center_vertical"
        android:layout_height="40dp"
        android:paddingLeft="10dp"
        android:textSize="15sp" />

</LinearLayout>

This will create a view for spinner options.

Prepare a new java class named “CustomApinnerAdapter.java”

Write the below source code in “CustomApinnerAdapter.java”

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class CustomSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
    String[] vehicles;
    Context context;

    public CustomSpinnerAdapter(Context context, String[] vehicles) {
        this.vehicles = vehicles;
        this.context = context;
    }

    @Override
    public int getCount() {
        return vehicles.length;
    }

    @Override
    public Object getItem(int position) {
        return vehicles[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view =  View.inflate(context, R.layout.vehicle_spinner, null);
        TextView textView = (TextView) view.findViewById(R.id.spinner_text);
        textView.setText(vehicles[position]);
        return textView;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {

        View view;

        if (position == 0){

            view =  View.inflate(context, R.layout.vehicle_prompt, null);
            TextView textView = (TextView) view.findViewById(R.id.vehicle_prompt);
            textView.setText(vehicles[position]);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

        }else {
            view =  View.inflate(context, R.layout.vehicle_dropdown, null);
            TextView textView = (TextView) view.findViewById(R.id.vehicle_dropdown);
            textView.setText(vehicles[position]);
            textView.setTextColor(Color.BLACK);
        }

        return view;
    }
}

In the above code, getView() method creates a layout for default spinner look.

In the getDropDownView() method, there are two scenarios.

I have used two files to generate two different views.

When the position is 0, means that for the very first time, we will use it as a prompt text creation.

At this time, we will generate view using vehicle_prompt.xml file.

In all other cases, (when position is not 0) we will generate drop down items which are spinner options, from which user will choose his desired option.

Following lines of coding are making a spinner with custom adapter

 CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, vehicles);
        spVehicle = (Spinner) findViewById(R.id.spVehicles);
        spVehicle.setAdapter(adapter);
        spVehicle.setSelection(1);

So the final code for MainActivity.java is as below

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;

public class MainActivity extends AppCompatActivity {

    boolean first = true;

    private String[] cars = {"Ferrari","Lamborghini","Rolls Roys"};
    private Spinner spCars;

    private String[] country = {"India","USA","Canada"};
    private Spinner spCountry;

    private String[] fruits = {"Select One Fruit","Mango","Orange","Strawberry"};
    private Spinner spFruit;

   private String[] vehicles = {"Custom Prompt Texts","Bike","Cars","Air Craft"};
    private Spinner spVehicle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spCars = findViewById(R.id.spCars);
        spCars.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, cars));

        spCountry = findViewById(R.id.spCountry);
        spCountry.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, country));
        spCountry.setPrompt("Spinner Prompt Programatically!!!");

        spFruit = findViewById(R.id.spFruits);
        spFruit.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, fruits));
        spFruit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(first){
                    first = false;
                }else {

                    if (position == 0) {
                        Toast.makeText(MainActivity.this, "Please select appropriate option!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, fruits[position] + " Selected !", Toast.LENGTH_SHORT).show();
                    }
                }
            }

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

            }

        });

        CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, vehicles);
        spVehicle = (Spinner) findViewById(R.id.spVehicles);
        spVehicle.setAdapter(adapter);
        spVehicle.setSelection(1);

    }
}