Search code examples
androidandroid-recyclerviewsharedpreferencesandroid-spinner

Spinner selections made in RecyclerView are getting reset when scrolled out of view


In Android, what are some ways to prevent Spinners in a RecyclerView from getting reset when the spinners move out of view? They all have same Id, so it's not possible to save the selections in the ShardPreferences object. And I don't think saving the state of the entire activity is applicable here either.


Solution

  • You can do this workaround create a HashMap inside your adapter of the positions of your items and the value will be the selected index in spinner or you can add an attribute to your model called spinnerIndex to save the index in your item all your work will be inside the onBindViewHolder example

    public class Item {
    
        int spinnerSelectedIndex;
    
        public int getSpinnerSelectedIndex() {
            return spinnerSelectedIndex;
        }
    
        public void setSpinnerSelectedIndex(int spinnerSelectedIndex) {
            this.spinnerSelectedIndex = spinnerSelectedIndex;
        }
    }
    

    inside your onBindViewHolder

    spinnerObject.setSelection(getSpinnerSelectedIndex());
    

    and you get your index filled from onItemSelected callback like this when sett the listener for spinner

    spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                    item. setSpinnerSelectedIndex(arg2)
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
    
            }
        });