Android Spinner: Set selected item as default

后端 未结 4 494
甜味超标
甜味超标 2021-01-14 06:22

I am making an android app that asks for the users to select a country via spinner.

When the user opens the app first time, user selects a country from list.

<
4条回答
  •  粉色の甜心
    2021-01-14 06:40

    You can use SharedPreferences to store the selection the first time that the user selects a country, and then use SharedPreferences again for the app to remember the selection, when the user returns a second time.

    To store the selection in a SharedPrefence:

    SharedPreferences.Editor editor = getPreferences(0).edit();
    int selectedPosition = yourSpinner.getSelectedItemPosition();
    editor.putInt("spinnerSelection", selectedPosition);
    editor.apply();
    

    To load the selection onto the spinner when reusing the app:

    SharedPreferences prefs = getPreferences(0);
    yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
    

    Hope this solves your issue :)

提交回复
热议问题