Android Spinner Disable Item Dropdown Selecetd Item | Close Dropdown

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

You are reading Android Spinner Disable Item Dropdown example tutorial.

Learn to hide/close android spinner dropdown programmatically in this example.

Disable an item which is currently selected, from the dropdown menu or pop up.

Generally, we use spinner to allow user to select any one item among multiple options.

Sometimes, developer wants to disable the current selected item in the dropdown menu. In this scenario user will not be able to click on that item from dropdown.

There are some occasions when there is only one option in the spinner. Here, we do not need to show dropdown.

You will learn how to handle all these tricky things about spinner in today’s tutorial.

View Disable Item

Step 1. Closing or Hiding Dropdown Menu Programmatically

You need to close or hide the whole dropdown menu when you have only one item in your spinner.

Let us achieve this goal. First, create a new project in android studio.

Add the below source code in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Below spinner have only one value, so disable it's dropdown"/>

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

 </LinearLayout>
  • I have taken one button and one spinner in above layout file.
  • Button is just saying that below spinner have single value so it has no dropdown menu.

Now write the following code in MainActivity.java file

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

public class MainActivity extends AppCompatActivity {

    private String[] heaven = {"Heaven"};
    private Spinner spHeaven;

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

        spHeaven = findViewById(R.id.spinner);
        // Initializing an ArrayAdapter
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,heaven);
        spHeaven.setAdapter(spinnerArrayAdapter);

        spHeaven.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
  }
}
  • First of all, compiler will create one string array variable named “heaven”.
  • This variable have only one item.
  • Then an object of spinner is defined.
  • In onCreate() method, we will find the spinner from layout file using it’s unique ID.
  • After this, compiler will create the array adapter using string array variable. (heaven).
  • And then it will set the adapter to our spinner.

Now read the following code block.

  spHeaven.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
  • Compiler will execute above code when the user touches the spinner.
  • I do not have set any code for this method. It simply means that we are telling the compiler to do nothing when the user touches the spinner.
  • Generally, when the user touches the spinner, system will open the dropdown. But in this case, we are overriding this general approach via above code structure.
  • So we have handle the scenario with only one item in the spinner.

Now let us disable the selected item in dropdown.

Step 2. Disable particular Item in Dropdown

First of all, add the below code in activity_main.xml file

 <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Selected Value is disable in dropdown of Below spinner"/>

    <Spinner
        android:id="@+id/spColors"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:spinnerMode="dropdown"/>
  • Same as we have added earlier. One button and one spinner.
  • Button is telling that selected item will be disabled in dropdown of the below spinner.
  • To handle the complex scenario of disabling a particular item in dropdown, we need to create custom adapter.

Drawable files

  • Before adapter first create a XML file under res->drawable directory.
  • Name of this file should be color_main.xml 

Add the below code structure in color_main.xml file

<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/main"
        android:singleLine="true"
        android:layout_marginLeft="50dp"
        android:text="At res"
        android:textColor="#000"
        android:textSize="20sp"
        android:gravity="center_vertical" />

</LinearLayout>
  • Above will create the view for main layout of the spinner.
  • To change the background color of spinner or text color and size of spinner, you can change these properties in the above textview.
  • Make another XML file in res->drawable directory.
  • Give it a name as color_dropdown.xml

Code block for color_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
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/dropdown"
        android:layout_width="match_parent"
        android:gravity="center_vertical"
        android:layout_height="50dp"
        android:paddingLeft="10dp"
        android:textColor="#f20a0a"
        android:textSize="15sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="#ad10af"/>

</LinearLayout>
  • This code will generate user interface for dropdown menu.
  • Every item of dropdown will inflate their text color and size from the above textview.
  • We can change text color and size for every spinner item via adapter class.

So let us prepare an adapter class.

Adapter Class

Create a new JAVA class named “ColorAdapter.java”

Write the following lines in “ColorAdapter.java” file

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import java.lang.reflect.Method;

public class ColorAdapter extends BaseAdapter implements SpinnerAdapter {
    String[] brands;
    Context context;

    public ColorAdapter(Context context, String[] brands) {
        this.brands = brands;
        this.context = context;
    }

    public static void hideSpinnerDropDown(Spinner spinner) {
        try {
            Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
            method.setAccessible(true);
            method.invoke(spinner);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    @Override
    public Object getItem(int position) {
        return brands[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.color_main, null);
        TextView textView = (TextView) view.findViewById(R.id.main);
        textView.setText(brands[position]);
        return textView;
    }

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

        View view;
        view =  View.inflate(context, R.layout.color_dropdown, null);
        final TextView textView = (TextView) view.findViewById(R.id.dropdown);
        textView.setText(brands[position]);

        final int positionss = position;

        if(MainActivity.selectedColor == positionss){
            textView.setTextColor(Color.parseColor("#FFAEADAD"));
        }

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(MainActivity.selectedColor == positionss){

                }else {
                    MainActivity.spColors.setSelection(positionss);
                    hideSpinnerDropDown(MainActivity.spColors);
                }
            }
        });


        return view;
    }
}
  • Look at the method named hideSpinnerDropDown() method in above code.
  • This method will help us to hide the dropdown when user selects the item.
  • getView() method will create the view for the spinner’s main layout.
  • We will use color_main.xml file in getView() method.
  • getDropDownView() method will help us to make the layout of every single item of the dropdown.

Below code will change the color of the selected item

 if(MainActivity.selectedColor == positionss){
            textView.setTextColor(Color.parseColor("#FFAEADAD"));
   }

Following code will disable the current selected item.

 textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(MainActivity.selectedColor == positionss){

                }else {
                    MainActivity.spColors.setSelection(positionss);
                    hideSpinnerDropDown(MainActivity.spColors);
                }
            }
        });

Step 3. Ending Updates

Now copy the below code in MainActivity.java

  public static int selectedColor = 0;
    private String[] colors = {"Red","Yellow","Green","Orange","Blue","White"};
    public static Spinner spColors;
  • You should add the three lines before the onCreate() method.
  • integer variable called selectedColor will maintain the current selected position of the spinner.

Write down the following source code in side the onCreate() method.

   spColors = findViewById(R.id.spColors);
        ColorAdapter adapter = new ColorAdapter(this, colors);
        spColors = (Spinner) findViewById(R.id.spColors);
        spColors.setAdapter(adapter);

        spColors.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedColor = position;
            }

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

            }
        });
  • First compiler will find the ID of the spinner.
  • Then it will create the object of ColorAdapter class and will set it to the adapter.
  • When the user selects the spinner item, compiler will update the value of the selectedColor variable.

Download Source Code For Android Spinner Disable Item Dropdown

[sociallocker]Download Source Code For Spinner_DisableItemDropdown[/sociallocker]