我遇到了一个有关保存由Button
修改的整数的问题。按下Button
时,整数值上升;但是,当我关闭并重新打开应用程序时,整数不会被保存。我将不胜感激任何帮助。
public class MyActivity extends Activity implements View.OnClickListener {
public static final String PREFS_NAME = "MyPrefsFile";
Button btn1;
Button btn2;
Button btn3;
Button btn4;
Button save;
TextView textTitle;
EditText scoreText;
EditText scoreText2;
int counter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btn1 = (Button) findViewById(R.id.add);
btn2 = (Button) findViewById((R.id.sub));
scoreText = (EditText) findViewById(R.id.intro);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
scoreText.setText(prefs.getString("autosave" , ""));
scoreText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do nothing
}
@Override
public void afterTextChanged(Editable s) {
prefs.edit().putString("autosave", s.toString()).commit();
}
});
@Override
public void onClick(View v) {
if (v == btn1) {
counter++;
scoreText.setText(Integer.toString(counter));
} else if (v == btn2) {
counter--;
scoreText.setText(Integer.toString(counter));
}
}
}
答案 0 :(得分:0)
首先,尝试将commit()行移动到onTextChanged()回调并添加一个Log.d()调用以帮助您进行调试。
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("onTextChanged", s.toString());
prefs.edit().putString("autosave", s.toString()).commit();
}
修改文本时检查日志以确保触发回调。
如果这不起作用,我建议将commit()行移动到onClick()回调。
@Override
public void onClick(View v) {
if (v == btn1) {
counter++;
scoreText.setText(Integer.toString(counter));
prefs.edit().putString("autosave", scoreText.getText()).commit();
} else if (v == btn2) {
counter--;
scoreText.setText(Integer.toString(counter));
prefs.edit().putString("autosave", scoreText.getText()).commit();
}
}