我正在开发一个应用程序,该应用程序具有一些开关按钮,这些按钮具有SharedPreferences
,因此当应用程序关闭和重新打开时,以前激活的按钮保持不变。
MainActivity类中的SharedPreferences:
private Spinner spipol;
private Switch quim, fil, fis, tri, esp, engl, inf, eti, reli, est, pol, dib, edf, mate;
private SharedPreferences sharedPreferences, sharfil, sharquim, shardfis, shartrig, sharesp, sharemater, sharing, sharinf, shareti, sharrel, sharest, sharpol, sharedf;
public static final String ex1 = "switch1";
public static final String ex = "switch";
dib = (Switch) findViewById(R.id.switch1);
sharedPreferences = getSharedPreferences("dib", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
dib.setChecked(sharedPreferences.getBoolean(ex, false));
dib.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
editor.putBoolean(ex, true);
} else {
editor.putBoolean(ex, false);
}
editor.commit();
}
});
我需要的是知道我如何用开关按钮做一些类似的事情,但用我的微调器:
spipol = (Spinner) findViewById (R.id.spipol);
String [] options = {"", "Short assignment", "Workshop", "Study", "Questions", "Review"};
ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android.R.layout.simple_spinner_dropdown_item, options);
spipol.setAdapter (adapter);
}
我在互联网上搜索了如何做到这一点,但在我看到的所有地方,他们都使用了保存按钮,我想知道的是,我是否可以在不需要实现这个按钮的情况下做到这一步。
我试过了,但没用:
spipol.setOnItemSelectedListener (new AdapterView.OnItemSelectedListener () {
@Override
public void onItemSelected (AdapterView <?> parent, View view, int position, long id) {
CaptureSpinner = (String) parent.getItemAtPosition (position);
index = position;
System.out.println ("Index:" + index);
}
@Override
public void onNothingSelected (AdapterView <?> parent) {
}
});
}
public void savePreference (Context context, int index) {
SharedPreferences sharpref = getPreferences (getApplicationContext (). MODE_PRIVATE);
SharedPreferences.Editor editor = sharpref.edit ();
editor.putInt ("Data", index);
System.out.println ("Index:" + index);
editor.apply ();
}
}
首先需要将savePreference()
更改为以下代码。您不需要传递上下文或位置。您可以直接从Spinner中选择项目,以便能够在onStop()
上调用此方法
public void savePreference() {
SharedPreferences sharpref = getSharedPreferences("Spinner", MODE_PRIVATE);
SharedPreferences.Editor editor = sharpref.edit();
editor.putInt("Data", spipol.getSelectedItemPosition());
System.out.println("Index:" + spipol.getSelectedItemPosition());
editor.apply();
}
调用onStope()
方法中的上述方法:
@Override
protected void onStop() {
super.onStop();
savePreference();
}
在你的onCreate()
上,你只需要称之为:
spipol = findViewById(R.id.spipol);
String[] options = {"", "Short assignment", "Workshop", "Study", "Questions", "Review"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, options);
spipol.setAdapter(adapter);
// here to restore the last selected item
SharedPreferences sharpref = getSharedPreferences("Spinner", MODE_PRIVATE);
spipol.setSelection(sharpref.getInt("Data", 0));