Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Multiple Selection Spinner in Android

I am using below code to create a simple Spinner (only single selection is allow)

But now i would like to know how can i use spinner to make multiple selection, I know i can achieve this using Dialog but i have to use Spinner..

public class MainActivity extends Activity {

    Spinner spnr;

    String[] celebrities = {
            "Chris Hemsworth",
            "Jennifer Lawrence",
            "Jessica Alba",
            "Brad Pitt",
            "Tom Cruise",
            "Johnny Depp",
            "Megan Fox",
            "Paul Walker",
            "Vin Diesel"
    };

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

        spnr = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, celebrities);

        spnr.setAdapter(adapter);
        spnr.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) {

                        int position = spnr.getSelectedItemPosition();
                        Toast.makeText(getApplicationContext(),"You have selected "+celebrities[+position],Toast.LENGTH_LONG).show();
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub

                    }

                }
            );
    }

}
like image 447
Sophie Avatar asked Aug 31 '15 07:08

Sophie


People also ask

How do you multi select on Android?

To select multiple files press on as many files as you want to select and check marks will appear next to all of the selected files. OR you press the More options menu icon in the upper right corner of the screen and press Select.

How can we implement multi select in Recyclerview?

For multi selection, we need to add one variable in our POJO (Employee. java) named isChecked as boolean. Now the logic is when user clicks any item of the recyclerview, we just set to true this field. And in bind() method, first we check this flag (true or false) then we show check image depends on that.


1 Answers

Spinner by default cannot work for Multiple selection.

If you need it, you have to extend it, check here

Android Spinner with multiple choice

like image 193
Derek Fung Avatar answered Oct 11 '22 10:10

Derek Fung