恢复在屏幕上旋转值 [英] Restore values on screen rotation
问题描述
我已经创建了几个TextViews编程。当屏幕旋转,我失去所有添加的文本的意见和他们的文本值。什么是拯救他们和旋转后恢复的最佳途径。我使用的是tablelayout并添加行每行有四个textviews。我不想prevent设备旋转。
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.
推荐答案
您应该使用的onSaveInstanceState保存状态,然后重新创建它的onCreate。这同时适用于活动和片段,但我相信在方法上的知名度是一个有点不同(他们是公众片段)。
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
}
}
请注意,这是比使用onRetainNonConfigurationInstance好;该方法用于跨轮换(例如位图)实际上保持周围的物体,但是你想只存储字符串,从而使用捆绑为preferred。此外,onRetainNonConfigurationInstance不受片段的支持;它被替换setRetainInstance,你不希望使用出于同样的原因。
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.
这篇关于恢复在屏幕上旋转值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!