Reputation: 31
I have created several TextViews programmatically. When screen rotates I loose all added text views and their text values. What is the best way to save them and restore after rotation. I am using a tablelayout and adding rows each row has four textviews. I did not want to prevent device rotation.
Upvotes: 3
Views: 3628
Reputation: 6282
You should use onSaveInstanceState to save your state, and then recreate it in onCreate. This works for both Activities and Fragments, but I believe the visibility on the methods is a bit different (they're public for Fragments).
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("text1", text1.getText().toString());
// do this for each of your text views
// You might consider using Bundle.putStringArray() instead
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize all your visual fields
if (savedInstanceState != null) {
text1.setText(savedInstanceState.getString("text1", ""));
// do this for each of your text views
}
}
Note that this is better than using onRetainNonConfigurationInstance; that method is used to actually keep objects around across rotations (e.g. Bitmaps), however you want to just store the strings, and thus using a Bundle is preferred. Also, onRetainNonConfigurationInstance isn't supported by Fragments; it's been replaced with setRetainInstance, and you don't want to use that for the same reason.
Upvotes: 5
Reputation: 1249
You need to persist the state across Device Rotation. As your view gets created dynamically, you need to store all this information in a 'Model' appropriate for your application. Android developer website has more info.
"To retain an object during a runtime configuration change:
Override the onRetainNonConfigurationInstance() method to return the object you would like to retain. When your activity is created again, call getLastNonConfigurationInstance() to recover your object."
Take a look here: http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject
Upvotes: 0