我想存储微调器位置。这使我可以在打开应用程序时还原微调器。
当前,我的代码无法正常工作。它正在保存数据,但是当我打开应用程序时,我单击的最后一项没有打开。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
refRoomsNew.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
spinner = (Spinner)findViewById(R.id.spinnerMain);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, RoomsNew);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
String data = snapshot.getValue(String.class);
RoomsNew.add(data);
addListenerOnSpinnerItemSelection();
Integer spinnerNew = prefs.getInt("Spinner", 0);
// Log.d("Spinner", spinnerNew);
if(spinnerNew != null ) {
Log.d("spinnerNew", String.valueOf(spinnerNew));
spinner.setSelection(spinnerNew);
}
}
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
SharedPreferences.Editor editor = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE).edit();
editor.putInt("Spinner", indexValue);
editor.apply();
}
答案 0 :(得分:0)
您必须在设置适配器后立即设置位置。像这样:
spiner.setAdater();
SharedPreferences prefs = getSharedPreferences("...",Context.MODE_PRIVATE);
// If "Spinner" is not set, it will assign 0
Integer initialValue = prefs.getInt("Spinner", 0);
spinner.setSelection(initialValue);
然后,在onItemSelected
期间,您只需要存储值:
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
SharedPreferences.Editor editor = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE).edit();
editor.putInt("Spinner", position);
editor.apply();
}