androidspinnerandroid-spinneroncreateandroid-textinputlayout

Spinner values dissapear after rotation


I*ve got a simple "material spinner" implementation:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:id="@+id/filled_exposed_dropdown"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="none"/>

</com.google.android.material.textfield.TextInputLayout>

And my fragment onCreate method which populates the list

AutoCompleteTextView editTextFilledExposedDropdown;
ArrayAdapter<String> adapter = null;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    String[] type = new String[] {"Bed-sitter", "Single", "1- Bedroom", "2- Bedroom","3- Bedroom"};
    adapter =new ArrayAdapter<>( getContext(),R.layout.dropdown_menu_popup_item, type);
    editTextFilledExposedDropdown = view.findViewById(R.id.filled_exposed_dropdown);
    editTextFilledExposedDropdown.setAdapter(adapter);
}

The code works perfectly fine as long I don't choose an item and rotate the phone. Once I rotate the phone the onCreate method is called again but for some reason the only item which is available is the item I choose before. The menu does not show all the other items.

What might the cause be? I'm repopulating the arrayadapter on purpose just to make sure I work with the same objects when I rotate the phone.


Solution

  • Use a custom view. This is a bug from the materialdesign class which has not been fixed yet unfourtantly:

    public class ExposedDropdownMenu extends MaterialAutoCompleteTextView {
    
        public ExposedDropdownMenu(@NonNull @NotNull Context context) {
            super(context);
        }
        public ExposedDropdownMenu(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attributeSet) {
            super(context, attributeSet);
        }
    
    
        public ExposedDropdownMenu(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attributeSet, int defStyleAttr) {
            super(context, attributeSet, defStyleAttr);
        }
    
        @Override
        public boolean getFreezesText() {
            return false;
        }
    }