Multiselect spinner item in Android
Aneh Thakur
. 2 min read
In this tip i show you how we can select multiple item inside a spinner using checkbox in android. With the help of MultiSelectionSpinner class.
Multiselect spinner
Step 1. First add this class in your project which help you to achieve multiselect feature in your spinner.
package com.mutiselect; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.util.AttributeSet; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.SpinnerAdapter; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Created by Aneh Thakur on 5/7/2015. */ public class MultiSelectionSpinner extends Spinner implements OnMultiChoiceClickListener { String[] _items = null; boolean[] mSelection = null; ArrayAdapter<String> simple_adapter; public MultiSelectionSpinner(Context context) { super(context); simple_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item); super.setAdapter(simple_adapter); } public MultiSelectionSpinner(Context context, AttributeSet attrs) { super(context, attrs); simple_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item); super.setAdapter(simple_adapter); } public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (mSelection != null && which < mSelection.length) { mSelection[which] = isChecked; simple_adapter.clear(); simple_adapter.add(buildSelectedItemString()); } else { throw new IllegalArgumentException( "Argument 'which' is out of bounds."); } } @Override public boolean performClick() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMultiChoiceItems(_items, mSelection, this); builder.show(); return true; } @Override public void setAdapter(SpinnerAdapter adapter) { throw new RuntimeException( "setAdapter is not supported by MultiSelectSpinner."); } public void setItems(String[] items) { _items = items; mSelection = new boolean[_items.length]; simple_adapter.clear(); simple_adapter.add(_items[0]); Arrays.fill(mSelection, false); } public void setItems(List<String> items) { _items = items.toArray(new String[items.size()]); mSelection = new boolean[_items.length]; simple_adapter.clear(); simple_adapter.add(_items[0]); Arrays.fill(mSelection, false); } public void setSelection(String[] selection) { for (String cell : selection) { for (int j = 0; j < _items.length; ++j) { if (_items[j].equals(cell)) { mSelection[j] = true; } } } } public void setSelection(List<String> selection) { for (int i = 0; i < mSelection.length; i++) { mSelection[i] = false; } for (String sel : selection) { for (int j = 0; j < _items.length; ++j) { if (_items[j].equals(sel)) { mSelection[j] = true; } } } simple_adapter.clear(); simple_adapter.add(buildSelectedItemString()); } public void setSelection(int index) { for (int i = 0; i < mSelection.length; i++) { mSelection[i] = false; } if (index >= 0 && index < mSelection.length) { mSelection[index] = true; } else { throw new IllegalArgumentException("Index " + index + " is out of bounds."); } simple_adapter.clear(); simple_adapter.add(buildSelectedItemString()); } public void setSelection(int[] selectedIndicies) { for (int i = 0; i < mSelection.length; i++) { mSelection[i] = false; } for (int index : selectedIndicies) { if (index >= 0 && index < mSelection.length) { mSelection[index] = true; } else { throw new IllegalArgumentException("Index " + index + " is out of bounds."); } } simple_adapter.clear(); simple_adapter.add(buildSelectedItemString()); } public List<String> getSelectedStrings() { List<String> selection = new LinkedList<String>(); for (int i = 0; i < _items.length; ++i) { if (mSelection[i]) { selection.add(_items[i]); } } return selection; } public List<Integer> getSelectedIndicies() { List<Integer> selection = new LinkedList<Integer>(); for (int i = 0; i < _items.length; ++i) { if (mSelection[i]) { selection.add(i); } } return selection; } private String buildSelectedItemString() { StringBuilder sb = new StringBuilder(); boolean foundOne = false; for (int i = 0; i < _items.length; ++i) { if (mSelection[i]) { if (foundOne) { sb.append(", "); } foundOne = true; sb.append(_items[i]); } } return sb.toString(); } public String getSelectedItemsAsString() { StringBuilder sb = new StringBuilder(); boolean foundOne = false; for (int i = 0; i < _items.length; ++i) { if (mSelection[i]) { if (foundOne) { sb.append(", "); } foundOne = true; sb.append(_items[i]); } } return sb.toString(); } }
Step 2. Now add view in your activity file where you want.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity"> <com.mutiautocomplete.MultiSelectionSpinner android:id="@+id/mySpinner1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/getSelected" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Check"/> </LinearLayout>
Step3. Now open your MainActivity.java file in which you want to get you selected item.
package com.mutiselect; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import java.util.ArrayList; public class MainActivity extends ActionBarActivity { MultiSelectionSpinner spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Multi spinner spinner = (MultiSelectionSpinner) findViewById(R.id.getSelected); Button bt = (Button) findViewById(R.id.btn); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = spinner.getSelectedItemsAsString(); Log.e("getSelected", s); } }); } }
Hope this code help you.
happy coading 🙂
More Stories from
Get Started with TypeScript: A Beginner's Guide with Code Samples
TypeScript is a popular, powerful programming language that is a superset of JavaScript. If you're new to TypeScript, this beginner's guide is the perfect place to start. With clear explanations and code samples, you'll learn the basics of TypeScript and
TypeScript vs TSX: Understanding the Differences
This article delves into the key differences between TypeScript and TSX, two programming languages used for developing complex web applications. From syntax and static typing to React integration and code organization, learn which language is best suited
Learn about the different types of React hooks with code examples
React hooks are a powerful feature that allow you to use state and other React features inside functional components. In this tutorial, you will learn about the different types of hooks available in React, and see code examples of how to use them in your
A step-by-step guide to deploying a ReactJS app online
Learn how to deploy your ReactJS app to the internet with this comprehensive tutorial. From setting up a hosting platform to building and uploading your code, we'll cover all the steps you need to take to get your app live. Whether you're a beginner or an
What is React context API?
React Context is a way to share values that are considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. It allows you to avoid prop drilling, or the passing of props through multiple levels