我目前的FragmentStatePagerAdapter实现在每次viewpager调用时都会创建新的片段。
我想保存先前加载的片段的状态,并重新使用它们。
我认为要实现这一点,我必须实现InstantiateItem但不清楚如何?
这是FragmentStatePagerAdapter的代码
using System.Collections.Generic;
//using Android.App;
using Android.Views;
using Hollard.MLAM.Android.Fragments.Fna;
using Object = Java.Lang.Object;
using Android.Support.V4.App;
public FnaFragmentPagerAdapter(FragmentManager fm)
: base(fm)
{
_registeredFragments = new Dictionary<int, Fragment>();
}
public override Fragment GetItem(int position)
{
Fragment fragment = null;
switch ((FnaStep)position)
{
case FnaStep.First:
fragment = new FnaStep1Fragment();
break;
case FnaStep.Second:
fragment = new FnaStep2Fragment();
break;
case FnaStep.Third:
fragment = new FnaStep3Fragment();
break;
case FnaStep.Fourth:
fragment = new FnaStep4Fragment();
break;
case FnaStep.Fifth:
fragment = new FnaStep5Fragment();
break;
case FnaStep.Sixth:
fragment = new FnaStep6Fragment();
break;
default:
break;
}
return fragment;
}
public override int Count
{
get { return PageCount; }
}
public Fragment GetRegisteredFragment(ViewGroup container, int position)
{
global::Android.Support.V4.App.Fragment fragment = null;
if (!_registeredFragments.TryGetValue(position, out fragment))
{
InstantiateItem(container, position);
_registeredFragments.TryGetValue(position, out fragment);
}
return fragment;
}
}
public enum FnaStep
{
First = 0,
Second,
Third,
Fourth,
Fifth,
Sixth
}
}
请帮帮我如何实现FragmentStatePagerAdapter,以便它可以重用已创建的片段。
答案 0 :(得分:0)
您应该保存片段的实例,而不是每次都实例化它们。换句话说,而不是这一行
fragment = new FnaStep1Fragment();
你应该使用
fragment = _FnaStep1FragmentInstance;
这样在容器活动的构造函数中初始化了_FnaStep1FragmentInstance
。