android - 如何才能不重新创建 Fragment 视图?
阿神
阿神 2017-04-17 15:25:11
0
4
805

大家先看图,红色部分是一个 Fragment,右上角的放大镜用来点击弹出一个搜索的 Activity。这样有一个问题,弹出搜索 Activity 之后,红色框内的 Fragment 就被销毁视图了,这样每次返回就会重新创建视图,无意义地耗费用户流量,降低用户体验。

所以想请问,怎么样才能不让 Fragment 重新创建视图?


今天早上继续找原因,并看了一下包裹这个 Fragment 的 Activity 的生命周期,发现了一点猫腻。
正常情况下如第二张生命周期图,弹出新的 Activity 之后原 Activity 会执行 onStop 方法,返回后会执行 onRestart、onStart,只有进程被杀的情况下才会再次执行 onCreate 方法。

而现在我发现,点击搜索弹出 Activity 之后返回,原 Activity 竟然执行的是 onCreate,Fragment 又因为是在这里初始化的,所以才导致 Fragment 每次都会被重建。所以现在的问题是,为什么原 Activity 不走右边的生命周期而走了左边的生命周期。继续摸索中。。。


问题解决了,说下原因,是之前那人写的搜索 Activity 有问题,因为他让其销毁的时候是重新启动一个主页 Activity!而不是 finish!天哪,完全无法理解他这么做的意图。。。

阿神
阿神

闭关修行中......

reply all(4)
刘奇

fragment.hide() -> fragment.show() This way it won’t be redrawn~ (I forgot if this is the case), even if onCreateView(...) is called again, the view drawn for the first time will be retained, and the next time onCreateView(...) is called back, You can return the reserved oneView.

For example:

View rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_social, null);
            initViews(rootView);
        }
        return rootView;
    }
大家讲道理

How do you implement it so that the fragment is destroyed when a new activity is opened? I can’t think of such a situation in normal use

刘奇

Can you post more code details?
When a new Activity is opened under normal circumstances, the onStop method of the current Activity will be called back, and the onStop of the associated Fragment will also be called back. That is to say, the previous Activity should enter the stopped state, so the Fragment should also be stopped. state and should not be destroyed.

迷茫

I want to see the jump code.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template