RED_
RED_

Reputation: 3007

Custom Spinner always shows selected item, even when none is selected

Odd behaviour from my spinner. I have custom spinner that should show a string "Select Item:" when nothing has been selected. When something has been selected it should update with the selected item. I ran a setOnItemSelectedListener but it always a selected item. Basically the first in the list. Here is my getView() code:

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

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View row = inflater.inflate(R.layout.spinner_placeholder, parent, false);

        itemText = (TextView) row.findViewById(R.id.itemText);
        final String userSelection = spinner.getSelectedItem().toString();

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                itemText.setText(userSelection);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                itemText.setText("Select item below");
            }
        });
        return row;
    }

Does anyone know why this happens? I assume I have set it up correctly. I moved the setOnItemSelectedListener to the oncreate() outside of my custom adapter but it still showed the same results. When you load the page with the spinner, it shows the first item always, even before the user has selected anything.

Any help is appreciate, thanks in advance.

Upvotes: 1

Views: 1237

Answers (1)

NigelK
NigelK

Reputation: 8480

As long as a Spinner's adapter contains at least one item, one of those items will always be selected. By default that will be position zero, i.e. the first in the list as you are seeing here. With a Spinner, there really isn't a concept of no item being selected.

Also, onNothingSelected() doesn't do what you think it does. From the documentation:

"Callback method to be invoked when the selection disappears from this view. The selection can disappear for instance when touch is activated or when the adapter becomes empty."

The simple solution to your issue is to have the first item in your adapter's list set to 'Select item below'. Then elsewhere in your code, if getSelectedItemPosition() returns zero, you know that no valid selection has yet been made.

EDIT:

If using a cursor adapter, you can get a 'Please select' row as the first entry using a UNION. For example:

SELECT _id, item, 1 AS sort
FROM table
UNION
SELECT 0 AS _id, 'Please select' AS item, 0 AS sort
ORDER BY sort, date

Upvotes: 1

Related Questions