我正在开发一个简单的应用程序,我遇到了持久化动态创建的状态Spinner
。无论我为动态微调器选择什么,它总是重置为定义的第一个元素。我已经覆盖了onPause
andonResume
没有任何效果。任何帮助都会很棒。
public class MainActivity extends Activity {
private OnItemSelectedListener optionListener = getOptionListener();
// private OnItemSelectedListener specificListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Spinner)findViewById(R.id.optionsSpinner)).setOnItemSelectedListener(optionListener);
}
@Override
public void onPause()
{
super.onPause();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int generalIndex = ((Spinner)findViewById(R.id.optionsSpinner)).getSelectedItemPosition();
int specificIndex = ((Spinner)findViewById(R.id.specificOptions)).getSelectedItemPosition();
prefs.edit().putInt("general", generalIndex).putInt("specific", specificIndex).commit();
}
@Override
public void onResume()
{
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int generalIndex = prefs.getInt("general", -1);
int specificIndex = prefs.getInt("specific", -1);
((Spinner)findViewById(R.id.optionsSpinner)).setSelection(generalIndex);
((Spinner)findViewById(R.id.specificOptions)).setSelection(specificIndex);
}
private OnItemSelectedListener getOptionListener()
{
return new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
int resId;
String selectedOption = parent.getSelectedItem().toString();
if (selectedOption.equals(getString(R.string.color)))
resId = R.array.colorsArray;
else
resId = R.array.shapesArray;
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getBaseContext(), resId, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
((Spinner)findViewById(R.id.specificOptions)).setAdapter(adapter);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) { }
};
}