切换视图后保持视图状态?
我有一个有 2 个视图的 Android 应用程序,它偶尔会使用 setContentView(R.layout.viewname); 在它们之间切换,
但是当我切换回以前的视图时,它似乎已经丢失了所有状态从我离开它的时候开始。即编辑文本忘记了它们的内容,按钮忘记了它们是启用还是禁用等。
我能做些什么来防止这种情况发生?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是在 Android 中在两个“视图”之间切换的推荐方法。
通常,您仅在
Activity.onCreate()
中调用setContentView()
一次,指定包含您希望使用的所有视图的布局(当然您可以添加稍后将更多Views
添加到布局中的任何ViewGroups
)。引用 Activity 的文档:您可以通过多种方式解决此问题,具体取决于您的特定应用程序要求以及“视图”的含义。以下是一些:
将视图放入单独的布局中,并使它们成为两个单独活动的内容视图。当您切换回以前的视图时,字段中的数据将默认保存自己(以后不起作用!)。
将所有视图放入单个 Activity 的一个布局中。使用 View.setVisibility(...) 切换您希望在屏幕上显示的视图的显示和隐藏。隐藏的视图将保持其状态。
为每组视图使用一个
Fragment
(您将需要Android 兼容性库(如果您的目标是 Honeycomb/3.0 之前的应用程序)。您可以通过使用FragmentManager
启动FragmentTransaction
来添加或删除Fragment
。被删除的片段仍然保持其状态,并且一旦再次添加就会正确恢复。如果您有自定义视图,则可以通过实现 View.onSaveInstanceState() 和 View.onRestoreInstanceState()。 答案 对此来说是一个很好的参考。
This is not the recommended way of switching between two 'views' in Android.
Typically, you call
setContentView()
only once inActivity.onCreate()
, specifying a layout that contains all of the Views you wish to work with (you can of course add moreViews
to anyViewGroups
in your layout, at a later time). To quote the docs for Activity:You can solve this problem in multiple ways, depending on your specific app requirements, and on what you mean by a 'view'. Here are a few:
Put your views inside separate layouts and have them be the content view of two separate Activities. The data in the fields will save themselves by default, when you switch back to a previous view (does not work going forward!).
Put all your views inside one layout of a single Activity. Use View.setVisibility(...) to toggle the showing and hiding of views you wish to be on screen. Views which are hidden will keep their state.
Use a
Fragment
for each group of views (you will need the Android compatibility library if you are targeting an app for pre-Honeycomb / 3.0). You can add or remove aFragment
by starting aFragmentTransaction
with theFragmentManager
. Fragments which are removed still keep their state, and will restore correctly once added again.If you have a custom View, you can make sure it keeps its state by implementing View.onSaveInstanceState() and View.onRestoreInstanceState(). The answer provided by Qberticus is an excellent reference for this.
将视图保存到字段,然后加载变量。因此,如果您的第一个内容视图是
framelayout,保存
FrameLayoutlayout1; //activity变量,将第一个视图保存到其中,
然后当您再次加载它时,而不是从xml加载它,而是从变量加载它:
setContentview(布局1);
只要活动显然没有同时被清除,这应该会保存状态。
Save your view to a field, then load the variable. So if your first contentview is a
framelayout, save it
FrameLayout layout1; //activity variable, save the first view to it
then when you load it again, rather than loading it from the xml, load it from the variable:
setContentview(layout1);
This should save state, as long as the activity isn't purged in the meantime obviously.