我有以下活動。當我運行應用程序它只能工作一次,當我按storeBTN
或retrieveBTN
第一次後,我看到Textview
沒有變化,沒有關於運行store()
和retrieve()
功能的日誌。按鈕OnClickListener只能運行一次android
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button storeBTN = (Button) findViewById(R.id.button);
storeBTN.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
EditText et = (EditText) findViewById(R.id.editText);
int i = Integer.parseInt(et.getText().toString());
store(i);
}
});
Button retrieveBTN = (Button) findViewById(R.id.button2);
retrieveBTN.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
retrieve();
}
});
}
public void store(int newHighScore){
Log.d("Meeeeee", "store: "+newHighScore);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(this.MODE_APPEND);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
boolean b = editor.commit();
Log.d("Meeee", "store: commited? "+b);
retrieve();
return;
}
public void retrieve(){
SharedPreferences sharedPref = this.getPreferences(this.MODE_APPEND);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Log.d("meeee", "retrieve: "+highScore+" in mode: "+this.MODE_APPEND);
TextView scoreTV = (TextView) findViewById(R.id.textView);
scoreTV.setText(highScore+"");
return;
}
}
爲什麼在store()中使用'setContentView(R.layout.activity_main);''? –