Android FragmentStatePagerAdapter用于自定义视图

时间:2019-02-23 16:09:46

标签: android fragmentstatepageradapter

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

1 个答案:

答案 0 :(得分:0)

我自己解决了。我完全忘记了我所关心的“保存实例状态”。我是从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;
    }

}