Fragment knowledge summary, fragment knowledge
1. Why is Fragment called the fifth component?
Fragment saves more memory than Activity, and its switching mode is more comfortable. It uses no less than four components and has its own lifecycle, and must be attached to Activity.
2. How to Create Fragment by Activity
Static creation:
Dynamic Creation
FragmentManager fm = getSupportFragmentManager();FragmentTransaction ft = fm.beginTransaction();ft.add(R.id.fl_content, new MyFragment());ft.commit();
3. Differences between FragmentPageAdapter and FragmentPageStateAdapter
FragmentPageAdapter separates Fragment every time a page is switched. It is suitable for Fragment with fewer pages to save some memory, which will not affect the system memory much.
FragmentPageStateAdapter recycles the Fragment each time it switches the page. It is suitable for Fragment with more pages, so that it will not consume more memory.
4. Fragment Lifecycle onAttach() onCreate() onCreateView() onActivityCreated() onStart() onResume() onPause() onStop() onDestroyView() onDestroy() onDetach() 5. Fragment Communication Fragment calls the method in Activity: getActivity calls the method in Fragment: calls back the method in Fragment to call Fragment: FragmentManager. findFragmentById 6. replace, add, and remove methods of Fragment Replace: replace Fragment stack top page add: add Fragment to stack top page remove: remove Fragment stack top page