I want to explore layout, ui interaction and view updating.
Obtaining a reference to a view element is as simple as invoking:
increaseButton = (Button)findViewById(R.id.increaseButton);Some observations about activity lifecycle (from vogella.com):
If the user interacts with an activity and presses the Back button or if the finish() method of an activity is called, the activity is removed from the current activity stack and recycled. In this case there is no instance state to save and the onSaveInstanceState() method is not called.So it is important to handle the back button pressed event in order not to lose the state of the counter.
If the user interacts with an activity and presses the Home button, the activity instance state must be saved. TheonSaveInstanceState() method is called. If the user restarts the application it will resume or restart the last running activity. If it restarts the activity it provides the bundle with the save data to theonRestoreInstanceState() and onCreate() methods.
To deal with app state, you have to implement the methods
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("counterValue", counterValue);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey("counterValue")) {
counterValue = savedInstanceState.getInt("counterValue");
counterField.setText("" + counterValue);
}
super.onRestoreInstanceState(savedInstanceState);
}
To deal with app state in the case of the user pressing the back button, you have to deal with SharedPreferences like this:we have to provide a method to write the instance state:
public boolean writeInstanceState(Context c) {
SharedPreferences p = c.getSharedPreferences(
MainActivity.PREFERENCES_FILE, MODE_WORLD_READABLE);
SharedPreferences.Editor e = p.edit();
e.putInt(COUNTER_VALUE_KEY, this.counterValue)
return (e.commit());
}
and a method to read it:
public boolean readInstanceState(Context c) {
SharedPreferences p = c.getSharedPreferences(PREFERENCES_FILE,
MODE_WORLD_READABLE);
this.counterValue = p.getInt(COUNTER_VALUE_KEY, 0);
return (p.contains(COUNTER_VALUE_KEY));
}
Nessun commento:
Posta un commento