简体   繁体   English

未调用 Android 视图 onSaveInstanceState

[英]Android View onSaveInstanceState not called

I am working with CustomView which extends some Android view like FrameLayout.我正在使用 CustomView,它扩展了一些 Android 视图,如 FrameLayout。 In my layout I use a ViewPager with a custom PagerAdapter.在我的布局中,我使用带有自定义 PagerAdapter 的 ViewPager。

The problem is that my View did not restore it's state when the fragment is re-attached to the ViewPager/Activity.问题是当片段重新附加到 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.例如,我有三个片段,如果我滑动到最后一个片段并返回到第一个片段,则 ScrollView 不在我允许的位置:它返回到默认值,在顶部。

I know that with a PagerAdapter, not all fragment are active on the same time, basically juste the +1/-1.我知道使用 PagerAdapter,并非所有片段都同时处于活动状态,基本上只是 +1/-1。

I can't find why my View.onSaveInstanceState() is not called, so as onRestoreInstanceState.我找不到为什么我的 View.onSaveInstanceState() 没有被调用,比如 onRestoreInstanceState。

The easy answer : it's because I was not setting id to my view (custom or not).简单的答案:这是因为我没有将id设置为我的视图(自定义与否)。 Android didn't manage the onSaveInstanceState/onRestoreInstanceState if no id is set to the view.如果没有为视图设置 id,Android 不会管理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.因此,当我的 customView 扩展基本视图时,没有额外的属性,为视图设置 ID 解决了这个问题,因此 onSaveInstanceState/onRestoreInstanceState 被调用。

So to summary, use one of this approach :总而言之,请使用以下方法之一:

from XML来自 XML

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

OR from Java或来自 Java

yourCustomView.setId(R.id.myCustomView);

is last case, you add static id to res/values/ids.xml <item name="myCustomView" type="id"/>最后一种情况,您将静态 id 添加到 res/values/ids.xml <item name="myCustomView" type="id"/>

Saving State by Default默认保存状态

We now have everything in place for our view to save and restore its state.我们现在已经为我们的视图保存和恢复它的状态准备好了一切。 However, this will not happen by default.但是,默认情况下不会发生这种情况。 If you want instances of your view to save state automatically, you can add this line to the init method:如果您希望视图的实例自动保存状态,可以将此行添加到 init 方法中:

setSaveEnabled(true);

Whether or not to do this is up to you.是否执行此操作取决于您。 Even if your view does not save state by default, users of the view can always enable saving state by calling setSaveEnabled(true) , or by specifying android:saveEnabled=“true” in the layout xml.即使您的视图默认不保存状态,视图的用户始终可以通过调用setSaveEnabled(true)或通过在布局 xml 中指定android:saveEnabled=“true”来启用保存状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM