Android ListActivity - 在空列表和非空列表之间切换
鉴于下面的 xml 文件,我想在对象列表不为空时显示 ListView
,并希望在列表为空时显示 ViewStub
。我可以让它工作,但每当我更改屏幕方向时,我都会丢失添加到列表中的新数据。
基本上,每当我添加新对象时,我都会调用适配器的changeData() 方法,该方法会更改对象列表并调用方法notifyDataSetChanged()
。关于如何确保此更改在所有视图中持续存在有什么建议吗?
(XML 中有更多内容,但不相关):
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:id="@android:id/list"></ListView>
<ViewStub android:id="@android:id/empty"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:layout="@layout/empty" />
</FrameLayout>
Given my xml file below, I want to show the ListView
when my object list is not empty and I want to show the ViewStub
when my list is empty. I can get this to work, but whenever I change screen orientations, I lose the new data that I've added to my list.
Basically, any time I add a new object, I call my adapter's changeData() method which changes the object list and calls the method notifyDataSetChanged()
. Any advice on how to make sure this change persists across all views?
(There's more in the XML but it's irrelevant):
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:id="@android:id/list"></ListView>
<ViewStub android:id="@android:id/empty"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:layout="@layout/empty" />
</FrameLayout>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用 saveInstanceState
Bundle
来维护屏幕状态,该方法可在onCreate()
方法中使用。每次更改屏幕方向时都会调用
onCreate()
。这里有一个例子:[CLICK]
You have to maintain your screen state by using the savedInstanceState
Bundle
which is available in theonCreate()
method.Every time when you change your screen orientation
onCreate()
is called.here an example : [CLICK]
你在哪里保存数据?问题似乎是当您的 Activity 被销毁时,您没有将其保留在任何地方。您的 Activity 可能会在方向改变时被销毁,但是当您处于后台且系统内存不足时,也可能会发生这种情况。
我建议您将数据保存在 onPause、onStop 或 onDestroy 调用中的某个位置,然后在相应的 onResume、onStart 或 onCreate 中重新加载。
Where are you saving the data? The problem would seem to be that you are not persisting it anywhere when your Activity is destroyed. Your Activity can be destroyed on an orientation change, but this can also happen when you are in the background and the system runs low on memory.
I suggest you save the data somewhere in an onPause, onStop or onDestroy call, and reload it in the corresponding onResume, onStart or onCreate.