1

I am trying to insert an item into an Adapter that multiple Spinners are using. However when I insert into the adapter, I would like the Spinners to retain their original selection based off the object and not the position.

In the case below, the Spinner is originally selecting "four", but when I click the button to insert "three", the spinner is now set to "three" instead of updating to the new position of "four". How can I achieve this?

public class MyActivity extends Activity {
List list;

ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    list = new ArrayList<>();
    list.add("one");
    list.add("two");
    list.add("four");
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
    spinner.setAdapter(adapter);

    // set selection to "four"
    spinner.setSelection(2);

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //list.add(2, "three") causes the same problem
            adapter.insert("three", 2);
            adapter.notifyDataSetChanged();
        }
    });
}
BinaryShrub
  • 346
  • 1
  • 3
  • 14

2 Answers2

0

Should you call spinner.setAdapter(adapter); or a similar method after inserting a new value into the adaptor?

Luke Allison
  • 3,118
  • 3
  • 24
  • 40
  • The item shows up in the spinner correctly, my issue is that the Spinner selection is set by index and not Object Reference. So I am trying to think of a way to do this dynamically for an adapter that can be used for many Spinners on the same screen. – BinaryShrub Dec 15 '15 at 02:23
  • Sorry, excuse my ignorance. http://stackoverflow.com/questions/11072576/set-selected-item-of-spinner-programmatically . This may help you. You could simply reload the spinners at the current index, which may be index-1 in your case. – Luke Allison Dec 15 '15 at 02:41
0
spinner.setSelection(list.indexOf("four"));

This will set the selection to "four" no matter on what position it is.

Mann
  • 560
  • 3
  • 13