0

I have a ViewGroup that programmatically instantiates and assigns an ID to a ViewPager. On rotation, the "Up" button and changing the screen orientation will recreate the Views -- but it doesn't remember the last page index of the ViewPager.

I've verified that OnSaveInstanceState() and OnRestoreInstanceState() are both being called, and both of them contain the correct page index information. But, the ViewPager gets reset to page index to 0 regardless. I notice that I get I message in the console

No package identifier when getting name for resource number [id that I programmatically defined]

As an experiment, I defined the ViewPager (along with the ID) in XML. It does correctly set the ViewPager to the last page index.

So, what I suspect is that the Android framework can't actually restore the last state correctly because the ID doesn't persist when the ViewGroup then ViewPager gets destroyed.

How can I get this to work? I'd like to contain all state relating things within this ViewGroup (eg avoid keeping track of the ViewPager position in Fragment). But, it doesn't seem like I can get this to work unless I can make the ID persist (if that's the root cause).

4

2 回答 2

0

编辑:我的代码中有一个竞争条件。在确保我有一个唯一的 ID 之后,它工作得很好。

在我看来(出于某种奇怪的原因),小于 10 的 ID 会向 ViewPager 的 OnRestoreInstanceState() 返回不正确的实例数据(可能来自另一个视图)。

真的很奇怪,因为我FindViewByID在设置 ID 之前使用过以确保 ID 是唯一的。但是,可能存在竞争条件或我缺少的东西。

无论如何,将 ID 设置为 10 或更大会给出正确的行为,并且 ViewPager 的位置在方向更改之间仍然存在。

于 2013-08-01T18:32:14.743 回答
0

从 OP 的帖子到现在已经两年了,但我认为值得在这里为我之后的人提及一些可能的问题。

在 OP 的原始帖子中,以编程方式恢复您设置的 id 的解决方案是将视图的 id 保存在其父级别。因此,当恢复时,父级将重新创建视图并将恢复的 id 设置回新视图。这样,您可以在配置更改之前恢复您保存在此视图中的所有数据。

在 OP 自己的答案中,我的猜测是您将相同的 id 分配给多个视图。例如,您有视图 A 和视图 B,并且您不小心将相同的 id 设置为两者。稍后,当您尝试在配置更改后从视图 A 恢复已保存状态时,您可能已恢复 B 的已保存状态。因此,您得到的实例数据不正确。Note B 可能不是普通视图,也可能是菜单项或操作系统认为的任何视图。您设置 id 大于 10 的解决方案只是因为您的第二个视图(B)的 id 小于 10,所以这次您很幸运。挖掘你的代码,看看你是否犯了我犯的同样的错误。

于 2015-06-01T16:34:06.360 回答