gpt4 book ai didi

android - Fragment 在滑动 ViewPager 时不调用 onSaveInstanceState?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:28 27 4
gpt4 key购买 nike

我的 ViewPager 有问题,我的 ListView 失去了它的滚动位置。

ListView 的状态可以使用以下方式轻松存储和恢复:

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.frag_cool_things, container, false);

AdvListView listView = (AdvListView) v.findViewById(R.id.lv0);
listView.setOnItemClickListener( mOnListItemClicked );

if (null != savedInstanceState)
{
listView.onRestoreListViewInstanceState(savedInstanceState.getParcelable("list_state"));
}

mListView = listView;

return v;
}

@Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);

outState.putParcelable("list_state", mListView.onSaveListViewInstanceState());
}

然而,问题在于,当 fragment 被滑动时,onDestroyView() 被调用但从未调用 onSaveInstanceState (Bundle outState)

旋转屏幕等可以很好地恢复 ListView 状态,但是滑动我不知道如何正确恢复列表。

最佳答案

2011 年 12 月 17 日更新:
我实际上找到了保存 fragment 内容的正确方法。您必须使用 FragmentStatePagerAdapter。这个适配器正确地保存了 fragment 的状态! :)

旧:
好吧,我找到了一种方法来做到这一点。如果您认为这是一个巨大的禁忌,请分享您的意见! :P

这是我修复此问题的 FragmentBase 类:

public abstract class FragmentBase extends Fragment
{
private boolean mInstanceAlreadySaved;
private Bundle mSavedOutState;

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
if (null == savedInstanceState && null != mSavedOutState) {
savedInstanceState = mSavedOutState;
}

mInstanceAlreadySaved = false;
return onCreateViewSafe(inflater, container, savedInstanceState);
}

@Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
mInstanceAlreadySaved = true;
}

@Override
public void onStop()
{
if (!mInstanceAlreadySaved)
{
mSavedOutState = new Bundle();
onSaveInstanceState( mSavedOutState );
}

super.onStop();
}

public abstract View onCreateViewSafe (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
}

关于android - Fragment 在滑动 ViewPager 时不调用 onSaveInstanceState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8423155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com