Skip to content Skip to sidebar Skip to footer

Spinner Initialization In A Custom View

I try to make a custom view but I've got a problem with the spinner. When I launch the application everything is ok. Preferences are read and the spinner setSelection method work g

Solution 1:

I cannot really explain why your code is not working, but I would prefer to save the state of the spinner locally (I mean in the activity); it's the normal Android workflow for screen rotation.

Something like this:

StringMVV1="1";
StringMVV2="2";
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    mVv1 = (ValueView)findViewById(R.id.value1);
    mVv2 = (ValueView)findViewById(R.id.value2);

if (savedInstanceState != null) {
    mVv1.setSelection(savedInstanceState.getInt(MVV1),false);
    mVv2.setSelection(savedInstanceState.getInt(MVV2),false);
}
else{
    mVv1.setSelection(mPref.getInt("pref_val1", 0),false);
    mVv2.setSelection(mPref.getInt("pref_val2", 1),false);
    }
}

@OverridepublicvoidonPause() {
    SharedPreferences.Editor editor = mPref.edit();
    editor.putInt("pref_val1", mVv1.getSelectedItemPosition());
    editor.putInt("pref_val2", mVv2.getSelectedItemPosition());
    editor.commit();
    super.onPause();
}

@Overrideprotectedvoid onSaveInstanceState (Bundle outState) {
     super.onSaveInstanceState(outState);
outState.putInt(MVV1, mVv1.getSelectedItemPosition());
outState.putInt(MVV2, mVv2.getSelectedItemPosition());
}

My syntax is maybe not perfect because I wrote it in the SO editor but hope you got the idea: the status is written in the Preferences as soon as the Activity is paused but if the activity rotates (your method should work but maybe is there a cache to access to the preferences or something...) then, it'll use the specific bundle for it: the one which is filled just when the screen rotates and used when the screen is recreated.

Test it and say if it's working ;)

Post a Comment for "Spinner Initialization In A Custom View"