Fragment与Activity之间生命周期的关系

本篇文章讲Fragment生命周期和Activity生命周期的关系,如图:

可以看到Fragment的生命周期和它所在的Activity的生命周期是相关联的

看Demo:

public class MainActivity extends BaseActivity{

    private FrameLayout fragContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragContainer = findViewById(R.id.fragment_container);
        FragmentTest fragment = new FragmentTest();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_container,fragment);
        transaction.commit();
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }
}

在Activity中的FrameLayout添加一个fragment,打印他们的生命周期如下:

08-26 07:49:56.160 5905-5905/com.example.hp.playaudiotest E/MainActivity: onCreate
08-26 07:49:56.169 5905-5905/com.example.hp.playaudiotest E/Fragment: onAttach
08-26 07:49:56.170 5905-5905/com.example.hp.playaudiotest E/Fragment: onCreate
    onCreateView
08-26 07:49:56.172 5905-5905/com.example.hp.playaudiotest E/Fragment: onActivityCreated
    onStart
08-26 07:49:56.173 5905-5905/com.example.hp.playaudiotest E/MainActivity: onStart
08-26 07:49:56.176 5905-5905/com.example.hp.playaudiotest E/MainActivity: onResume
08-26 07:49:56.176 5905-5905/com.example.hp.playaudiotest E/Fragment: onResume
08-26 07:50:07.933 5905-5905/com.example.hp.playaudiotest E/MainActivity: onPause
08-26 07:50:07.934 5905-5905/com.example.hp.playaudiotest E/Fragment: onPause
08-26 07:50:08.502 5905-5905/com.example.hp.playaudiotest E/MainActivity: onStop
08-26 07:50:08.503 5905-5905/com.example.hp.playaudiotest E/Fragment: onStop
08-26 07:50:08.503 5905-5905/com.example.hp.playaudiotest E/MainActivity: onDestroy
08-26 07:50:08.503 5905-5905/com.example.hp.playaudiotest E/Fragment: onDestroyView
08-26 07:50:08.509 5905-5905/com.example.hp.playaudiotest E/Fragment: onDestroy
08-26 07:50:08.510 5905-5905/com.example.hp.playaudiotest E/Fragment: onDetach

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值