Android View onSaveInstanceState未调用 [英] Android View onSaveInstanceState not called

查看:361
本文介绍了Android View onSaveInstanceState未调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CustomView,它扩展了一些Android视图,例如FrameLayout.在我的布局中,我使用带有自定义PagerAdapter的ViewPager.

I am working with CustomView which extends some Android view like FrameLayout. In my layout I use a ViewPager with a custom PagerAdapter.

问题是,当片段重新附加到ViewPager/Activity时,我的视图 未恢复其状态.例如,我有三个片段,如果我滑动到最后一个片段并返回到第一个片段,则ScrollView不在我允许的位置:它返回默认值,位于顶部.

The problem is that my View did not restore it's state when the fragment is re-attached to the ViewPager/Activity. For example, I have three fragments, if I swipe to the last one and come back to the first, the ScrollView is not where I let it : it's back to default, on top.

我知道使用PagerAdapter,并非所有片段都在同一时间处于活动状态,基本上就是+ 1/-1.

I know that with a PagerAdapter, not all fragment are active on the same time, basically juste the +1/-1.

我找不到为什么未调用View.onSaveInstanceState()之类的原因,例如onRestoreInstanceState.

推荐答案

简单的答案:这是因为我没有在视图中设置 id (自定义或不自定义).如果未将id设置为视图,则Android不会管理onSaveInstanceState/onRestoreInstanceState.

The easy answer : it's because I was not setting id to my view (custom or not). Android didn't manage the onSaveInstanceState/onRestoreInstanceState if no id is set to the view.

因此,当我的customView扩展基本View时,没有额外的属性,因此为该视图设置ID就解决了该问题,因此应按需调用onSaveInstanceState/onRestoreInstanceState.

So as my customView was extending base View, with not extra property, setting an ID to the view solved the issue and so onSaveInstanceState/onRestoreInstanceState are called as it should.

总而言之,请使用以下一种方法:

So to summary, use one of this approach :

来自XML

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ...
    android:id="@+id/scrollView">
</ScrollView>

Java的OR

yourCustomView.setId(R.id.myCustomView);

是最后一种情况,您将静态ID添加到res/values/ids.xml <item name="myCustomView" type="id"/>

is last case, you add static id to res/values/ids.xml <item name="myCustomView" type="id"/>

这篇关于Android View onSaveInstanceState未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆