在没有要求onAttach,的onCreate,onCreateView等活动更换片段 [英] Replacing fragments in an activity not calling onAttach, onCreate, onCreateView, etc

查看:516
本文介绍了在没有要求onAttach,的onCreate,onCreateView等活动更换片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在这里有这块code的,我创建一个新的片段,并与另一片段取代它。这效果很好。不过我注意到,在第一行的构造函数被调用,但 onAttach()的onCreate()等不是。如果我取消注释它不会为<$​​ C $ C>的updateItem工作的第二行(URL)要求是在OnCreate()函数来启动网页视图。

So I have this piece of code here, I am creating a new Fragment and replacing it with another fragment. That works well. However I have notice that on the first line the constructor is being called but the onAttach(), onCreate() etc are not. If I were to uncomment the second line it won't work as updateItem(URL) requires a webView that is initiated in the onCreate() function.

DetailViewFragment detailFragment = new DetailViewFragment();
//detailFragment.updateItem(URL);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.displayList, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

请问AP preciate任何帮助,将得到与第二行工作注释。

Would appreciate any help that will get that to work with the second line uncommented.

推荐答案

onAttach()的onCreate()等,将不会被调用,直到 FragmentManager 实际上已经犯下的变化。于是,经过一段时间内提交()被称为上的转变。如果你需要的URL传递给片段从一开始,它添加到片段的说法捆绑的的调用提交()。然后,你就可以去的网址在的onCreate()或其他生命周期方法的访问。所以,你想是这样的:

The onAttach(), onCreate(), etc. will not be called until the FragmentManager has actually committed the change. So, some time after commit() is called on the transition. If you need to pass the URL to the Fragment from the start, add it to the fragment's argument bundle before you call commit(). Then you'll be able to get access to the URL in your onCreate() or other lifecycle methods. So you'll want something like this:

DetailViewFragment detailFragment = new DetailViewFragment();
Bundle args = new Bundle();
args.putString(DetailViewFragment.INIT_URL, URL);
detailFragment.setArguments(args);
ft.replace(R.id.displayList, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

现在在你的的onCreate()您可以致电 getArguments()来获得包和检索URL它被你的活动通过。

Now in your onCreate() you can call getArguments() to get the bundle and retrieve the URL which was passed by your activity.

这篇关于在没有要求onAttach,的onCreate,onCreateView等活动更换片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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