Android spinner acting weird on rotate

2019-07-22 11:49发布

问题:

I have a fragement with various Spinners in it. To have these spinners display an initial (non selectable) value I'm using a custom arrayAdapter (SpinnerHintAdapter). The only important thing this class does is override the getCount() so the last item of the selection-array isn't displayed, this is where the initial value is stored.
This all works fine untill you rotate the device, then the spinners are set on the last normal value of the list for some reason, even though the Fragment class still thinks it's set on the initial value.
Anyone any clue why this happens and / or how to solve this problem?

Code samples:
fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_free_top_up, container, false);
    Spinner pet = (Spinner) rootView.findViewById(R.id.pet);
    SpinnerHintAdapter<CharSequence> petAdapter = SpinnerHintAdapter.createFromResource(getActivity(),
        R.array.pet_array, android.R.layout.simple_spinner_item);
    petAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    pet.setAdapter(petAdapter);
    pet.setSelection(pet.getCount());
    return rootView;
}

SpinnerHintAdapter:

@Override
public int getCount() {
    int count = super.getCount();
    // The last item will be the hint.
    return count > 0 ? count - 1 : count;
}

example string-array

<string-array name="pet_array">
    <item>Yes</item>
    <item>No</item>
    <item>(initial value)</item>
</string-array>

回答1:

The activity is re-created when you rotate the device. You need to override onSavedInstanceState function, save your data in a Bundle and then use that data in onCreate again.

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //save your data
}

and then use that in your onCreate to restore your spinner.



回答2:

Haven't found an answer to this specific problem but used another method to display an initial value which can be found here: https://stackoverflow.com/a/12221309/3453217

Any clarification as to what went wrong with my first attempt is still welcome.