Fragment学习

Fragment学习,第1张

Fragment学习 Fragment学习 生命周期

—>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作为跳转。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5677345.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存