—>onAttach()
—>onCreate()
—>onCreateView()
—>onActivityCreated()
—>onStart()
—>onResume()
—>onPause()
—>onStop()
—>onDestroyView()
—>onDestroy()
—>onDetach()
总体来说分为Fragment的启动销毁和View的启动销毁。
1.layout文件
2.继承Fragment的实现类
3.在主VIew中创建Fragment控件,并将name属性设置为实现类的地址例如:
android:name=“com.demo.MFragment”
通过Replace加载:
public void replaceFragment(Fragment fragment){ FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.layou.book_fragment,fragment); fragmentTransaction.commit(); }
调用此方法即可动态加载Fragment,旧的Fragment则会销毁回收。
生命周期—>onAttach()—>onCreate()—>onCreateView()—>onActivityCreated()—>onStart()—>onResume()—>(新)onAttach()—>(新)onCreate()—>onPause()—>onStop()—>onDestroyView()—>onDestroy()—>onDetach()—>(新)onCreateView()—>(新)onActivityCreated()—>(新)onStart()—>(新)onResume()
但是添加了addToBackStack()方法后只会回收旧的Fragment中的View而Fragment则不会被销毁回收。
public void replaceFragment(Fragment fragment){ FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.layou.book_fragment,fragment); fragmentTransaction.addToBackStack(); fragmentTransaction.commit();
生命周期—>onAttach()—>onCreate()—>onCreateView()—>onActivityCreated()—>onStart()—>onResume()—>(新)onAttach()—>(新)onCreate()—>onPause()—>onStop()—>onDestroyView()—>(新)onCreateView()—>(新)onActivityCreated()—>(新)onStart()—>(新)onResume()
通信Activity—>Fragment
Fragment—>Activity
MyFragment mFragment = (MyFragment) getSupportFragmentManager() .findFragmentById(R.id.book_fragment);
MainActivity activity = (MainActivity) getActivity;
碎片之间的通信可以通过Activty作为跳转。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)