Android 自定义视图的 FragmentStatePagerAdapter

Android FragmentStatePagerAdapter for custom View

因为我不喜欢 Android 的底部导航栏的默认实现,所以我制作了自己的底部导航栏并将其与 FragmentStatePagerAdapter 连接。我只想知道如何像 viewpager 一样从我的适配器中获取已经创建的片段及其保存的实例状态? 如果有人能帮我解决这个问题就好了。

我自己解决了。我完全忘记了关心我视图中的保存实例状态。我从 ViewPager 源代码中获取并稍微修改了它,因为某些方法被标记为已弃用。这里实现。

@Nullable
@Override
protected Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    SaveState ss = new SaveState(superState);
    ss.position = lastSelectedPosition;
    ss.itemId = lastSelectedItemId;
    if (mAdapter != null) {
        ss.adapterState = mAdapter.saveState();
    }
    return ss;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (!(state instanceof SaveState)) {
        super.onRestoreInstanceState(state);
        return;
    }
    SaveState ss = (SaveState) state;
    super.onRestoreInstanceState(ss.getSuperState());
    if (mAdapter != null) {
        mAdapter.restoreState(ss.adapterState, ss.loader);
        setSelectedItem(ss.position, ss.itemId);
        lastSelectedItemId = ss.itemId;
        lastSelectedPosition = ss.position;
    }
}

public static class SaveState extends BaseSavedState {
    int position;
    int itemId;
    Parcelable adapterState;
    ClassLoader loader;

    SaveState(Parcelable superState) {
        super(superState);
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(position);
        out.writeInt(itemId);
        out.writeParcelable(adapterState, flags);
    }

    public static final Parcelable.ClassLoaderCreator<SaveState> CREATOR = new 
    Class later dater<SaveState>() {
        @Override
        public SaveState createFromParcel(Parcel source) {
            return new SaveState(source, null);
        }

        @Override
        public SaveState[] newArray(int size) {
            return new SaveState[size];
        }

        @Override
        public SaveState createFromParcel(Parcel source, ClassLoader loader) {
            return new SaveState(source, loader);
        }
    };

    SaveState(Parcel in, ClassLoader loader) {
        super(in);
        if (loader == null) {
            loader = getClass().getClassLoader();
        }
        position = in.readInt();
        itemId = in.readInt();
        adapterState = in.readParcelable(loader);
        this.loader = loader;
    }

}