我有一个活动,你有 3 个搜索栏,我在每个搜索栏的文本视图上看到每个搜索栏的值。
现在,我想用 sharedPreferences 存储每个搜索栏的值。我已经尝试了几种方法,但我无法得到它。
我读过正确的方法是在调用 onPause 时保存值,并在调用 onResume 时恢复它们。
public class Configuration extends Activity implements OnSeekBarChangeListener {
public TextView progress1;
public TextView progress2;
public TextView progress3;
private SeekBar bar1;
private SeekBar bar2;
private SeekBar bar3;
private int savedProgress1;
private int savedProgress2;
private int savedProgress3;
private int loadedProgress1;
private int loadedProgress2;
private int loadedProgress3;
private String Key_PROGRESS_1 = "bar1_progress";
private String Key_PROGRESS_2 = "bar2_progress";
private String Key_PROGRESS_3 = "bar3_progress";
SharedPreferences mPreferences;
SharedPreferences.Editor editor;
/*********************
*
* ONCREATE
*
********************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuracion2);
bar1 = (SeekBar)findViewById(R.id.fast_bar); //make seekbar object
bar1.setOnSeekBarChangeListener(this); //set seekbar listener
progress1 = (TextView)findViewById(R.id.salida1);
bar2 = (SeekBar)findViewById(R.id.climb_bar);
bar2.setOnSeekBarChangeListener(this);
progress2 = (TextView)findViewById(R.id.salida2);
bar3 = (SeekBar)findViewById(R.id.platform_bar);
bar3.setOnSeekBarChangeListener(this);
progress3 = (TextView)findViewById(R.id.salida3);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = mPreferences.edit();
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
Log.v("", "" + bar);
switch (bar.getId()) {
case R.id.fast_bar:
progress1.setText(progress + "%");
break;
case R.id.climb_bar:
progress2.setText(progress + "%");
break;
case R.id.platform_bar:
progress3.setText(progress + "%");
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekBar.setSecondaryProgress(seekBar.getProgress());
}
protected void onResume() {
super.onResume();
loadedProgress1 = mPreferences.getInt("Key_PROGRESS_1", 0);
bar1.setProgress(loadedProgress1);
loadedProgress2 = mPreferences.getInt("Key_PROGRESS_2", 0);
bar2.setProgress(loadedProgress2);
loadedProgress2 = mPreferences.getInt("Key_PROGRESS_3", 0);
bar3.setProgress(loadedProgress3);
}
protected void onPause(/*SeekBar seekBar*/) {
super.onPause();
savedProgress1 = bar1.getProgress();
editor.putInt(Key_PROGRESS_1, savedProgress1);
savedProgress2 = bar2.getProgress();
editor.putInt(Key_PROGRESS_2, savedProgress2);
savedProgress3 = bar3.getProgress();
editor.putInt(Key_PROGRESS_3, savedProgress3);
editor.commit();
}
}