简体   繁体   中英

how I can hide the element with index 0 from dropdown list in spinner

Please tell me how can I hide the item at index 0 from the dropdown in the spinner in Android Studio? I am using this code, it works, but when I open the list, it shows at the bottom. That is, it is focused on the elements below. what do i need to change?

SpinnerName = (Spinner) v.findViewById(R.id.spinner1);

        ArrayList<String> names = new ArrayList<>();

        names.add(0, "SELECT");
        names.add(1, "Name1");
        names.add(2, "Name2");
        

       final int listsize = names.size()-1;

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names){
            @Override
            public int getCount() {
                return(listsize); 
            }
        };

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpinnerName.setAdapter(adapter);
        adapter.setDropDownViewResource(R.layout.spinner_list);
        SpinnerName.setSelection(listsize);
       
       
        SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

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

                ....

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
SpinnerName.setSelection(listsize);

your problem is here, you are passing the total list size number and that where you are doing wrong. because setSelection method use to show default index of spinner.

you can simply do that SpinnerName.setSelection(1); that would give you the fist spinner item unless showing the names.add(0, "SELECT"); item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM