欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-14 08:11:58
...

本篇文章讲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