gpt4 book ai didi

android - 嵌套viewpager的setCurrentItem

转载 作者:搜寻专家 更新时间:2023-11-01 08:39:57 24 4
gpt4 key购买 nike

我有一个嵌套在 fragment 中的 ViewPager,当设备改变方向时,我想保存并恢复 ViewPager 所在的页面。我目前正在这样做:

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

// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());

setRetainInstance(true);

// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);

if(savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("pagerState"), false);
}
return mViewPager;
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("pagerState", mViewPager.getCurrentItem());
}

onSaveInstanceState 期间保存的值是正确的,在 onCreateView 旋转后 savedInstanceState.getInt("pagerState") 的值是也正确。但是没有任何反应,ViewPager 停留在其默认页面上,并且 logcat 中没有任何内容。我很难过。

最佳答案

经过几个小时的审查某些内容后,我提出了以下解决方案(我想这是一种通用的方法)。我包括您已完成的步骤和其他必要的步骤。

    1. 调用 setRetainInstance(true);(你已经完成了)
    1. 设置 Fragment 的保存状态。 (你已经做到了)
    1. 在 Host Activity 上,调用以下命令以确保您的 Fragment 已保存在 Activity 的状态中:

这是一个 fragment :

... (other stuffs)

Fragment mainFragment; // define a local member

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// After you rotate your screen, by default your Activity will be recreated
// with a bundle of saved states, i.e at this point, savedInstanceState is
// not null in general. If you debug it, you could see how it saved your
// latest FragmentTransactionState, which hold your Fragment's instance

// For safety, we check it here, and retrieve the fragment instance.
mainFragment = getSupportFragmentManager().findFragmentById(android.R.id.content);
if (mainFragment == null) {

// in very first creation, your fragment is null obviously, so we need to
// create it and add it to the transaction. But after the rotation, its
// instance is nicely saved by host Activity, so you don't need to do
// anything.

mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, mainFragment)
.commit();
}
}

这就是我所做的一切,让它发挥作用。希望这会有所帮助。

关于android - 嵌套viewpager的setCurrentItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726697/

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