G
G
geron2016-01-27 11:58:56
Android
geron, 2016-01-27 11:58:56

How to remove an element from Spinner?

Hello!
I am using MaterialSpinner and ArrayAdapter. There is no hint in the spinner, so an empty string is added to the adapter as the first element so that empty spinners are visible on the screen. After selecting an element (not an empty line), the empty line is removed. The problem is that when an element is selected from the spinner for the first time, the element following it is not selected and onItemSelected does not work, you can select only through one element. I suspect that this is due to the removal of the element.
I tried several options, two of them are the best.
1(first try) doesn't work.

list.remove(StringUtil.EMPTY_STRING);
adapterCategory.notifyDataSetChanged();

1(second attempt) - Re-created the adapter, in the onItemSelected method.
list.remove(StringUtil.EMPTY_STRING);
adapterCategory = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, list);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapterCategory);
spinnerCategory.setSelection(position - 1);

In the second case, everything works, the next element is selected.
Only when the next element is selected, the very first element in the spinner is shown for a fraction of a second.
Colleagues, please tell me the correct solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
ferosod, 2016-01-27
@ferosod

1. Make your own adapter by deriving from ArrayAdapter.
2. In public View getDropDownView() check if position >= getCount() return empty View.
3. After spinnerCategory.setAdapter(adapterCategory); call spinnerCategory.setSelection(adapterCategory.getCount())
In this case, immediately after the adapter is assigned, an empty spinner will appear, but as soon as it is first clicked, the empty string will disappear from the selection options. You can write there not an empty string, but for example, a hint like "Select a characteristic".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question