恢复在屏幕上旋转值

编程入门 行业动态 更新时间:2024-10-26 19:34:33
本文介绍了恢复在屏幕上旋转值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经创建了几个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.

更多推荐

恢复在屏幕上旋转值

本文发布于:2023-07-09 00:22:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082137.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:屏幕上

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!