片段 - 我应该重用视图onCreateView,我应该怎么办呢? [英] Fragment - should I reuse view in onCreateView and how should I do that?

查看:126
本文介绍了片段 - 我应该重用视图onCreateView,我应该怎么办呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实,我总是重复我的观点在我的片段如下所示:

Actually, I always reused my view in my fragments like the following:

private View mView = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    if (mView == null)
        mView = inflater.inflate(R.layout.view);
    return mView;
}

这工作,与viewpager等。现在,我开始使用我的简单的活动片段,以及如果,且仅当,我的片段添加到backstack,这将失败,因为java.lang.IllegalStateException的:指定的孩子已经有父。你必须先调用removeView()孩子的父母。

所以,我的问题是:

  • 在它是确定的,如果我检查的意见父,将其删除,并把它添加到新的父?
  • 或者我应该始终重新创建视图,永不重用呢?如果是的话,为什么
  • 还有没有其他的点,其中重用的观点会失败?

推荐答案

也许这可以帮助理解的行为。如果检查出<一href="https://github.com/grantland/android-support-v4/blob/master/src/java/android/support/v4/app/FragmentManager.java#L377"相对=nofollow> FragmentManagerImpl.java 你会发现以下内容:

Maybe this can help to understand the behavior. If you check out FragmentManagerImpl.java you will find the following:

首先,我们创建一个视图通过调用 onCreateView()行845 的),然后我们换用另一种观点认为,这成为创建的视图我们认为母公司(行848-849 的)。这意味着我们认为不会成为真正的容器的孩子,但它是一个包装视图的孩子现在。重用的问题发生,当视图获取从容器中取出(行998 的)。 FragmentManager从容器中删除包装观点,但我们真正认为保持加入到包装查看本身。这是什么原因造成您遇到的问题。

First we create a view by calling onCreateView() (line 845) and then we wrap created view with another view, which becomes a parent of our view (lines 848-849). This means our view does not become a child of real container, but it's a child of a wrapper view now. The problem with reuse happens, when view gets removed from the container (line 998). FragmentManager removes wrapper view from the container, but our real view stays added to the wrapper view itself. This is what causes the issue you experience.

即使知道这一点,我不会建议重用视图片段也因为观点可以活多一点的时间比碎片,因为它们可以在即使在片段被摧毁消失动画中使用。如果您尝试从其父当时删除这样的观点,那么动画可能会被打破。

Even knowing this, I would not suggest to reuse views in the fragment also because views can live a bit longer than fragments, because they can be used in "disappearing" animations even after the fragment is been destroyed. If you try to remove such a view from its parent at that time, then the animation might be broken.

另一种说法不缓存视图中缺少 onCreateView()办法convertView参数。还记得 ListAdapter 允许重复使用设计的看法? Android的负责缓存和适当的再利用这些观点。这是不与片段虽然如此。

Another argument to not cache the view is missing "convertView" parameter from the onCreateView() method. Remember ListAdapter allowing to reuse the views by design? Android takes care for caching and proper reusing those views. This is is not the case with fragment though.

这篇关于片段 - 我应该重用视图onCreateView,我应该怎么办呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆