Android Fragment导航返回上一页

时间:2019-09-21 12:23:31

标签: android navigation android-jetpack

我正在尝试在项目中使用一项活动。 在主片段中,用户浏览和Tab布局中,ViewPager包含五个片段,在第一个片段中包含两个片段,形成一个片段导航到新片段,当返回时,我丢失了ViewPager片段中的所有数据。

就像这样 enter link description here

@Ail告诉我。我修复了这个错误。

之前的代码:

protected View mView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(getRootView(), container, false);
    initView();
    initData();
    return mView;
}

后面的代码:

public View mView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (mView == null) {
        mView = inflater.inflate(getRootView(), container, false);
        initView();
        initData();
    }
    return mView;
}

1 个答案:

答案 0 :(得分:1)

您拥有一个Activity,这意味着您正在使用体系结构导航组件。

当您导航回到主屏幕时,将调用诸如onViewCreated之类的回调方法。根据 Ian Lake 的建议,您应该保留对您在主屏幕中首次创建的View的引用,然后再次返回该视图:

https://twitter.com/ianhlake/status/1103522856535638016

还要看看Fragments destroyed / recreated with Jetpack's Android Navigation components

相关问题