Search code examples
androidandroid-spinnerandroid-lifecycle

How to handle Spinners when screen orientation changes?


I have two Spinners. In onCreate i setup listeners for them. At some other places i populate them.

Now I am not sure what the best practice is for handling these spinners when screen orientation changes. Should i store all values and selected item in sharedPreferences somehow or in savedInstanceState?

If you can, please advise me in a prefered way and also include some sample code for handling spinners. The goal here is to keep the values and selected item thru the lifecycle.

I will include code at request or if needed.

Thanks


Solution

  • Add android:configChanges="orientation|screenSize" in your AndroidManifest file, it will keep spinner value selected on orientation change.

    User Spinner Like this:

    mSpinner = findViewById(R.id.spinner);
    
        ArrayList<String> stringArrayList = new ArrayList<>();
    
        for (int i = 0; i < 6; i++) {
    
            stringArrayList.add("List Item " + i);
    
        }
    
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringArrayList);
        spinner.setAdapter(arrayAdapter);