📅  最后修改于: 2023-12-03 14:39:11.769000             🧑  作者: Mango
Android中的片段是应用程序的一个重要组成部分,它可以通过Activity添加到用户界面中。片段生命周期是指片段从创建到销毁的整个过程。
一个片段从创建到销毁的全过程可以分为以下事件:
下面是生命周期方法的调用顺序:
public class MyFragment extends Fragment {
// 1. Called when a fragment is first attached to its activity.
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
// 2. Called to do initial creation of the fragment.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// 3. Called once the fragment view has been created.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout, container, false);
}
// 4. Called once the parent activity and its views have been created.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
// 5. Called when the fragment is visible to the user and actively running.
@Override
public void onStart() {
super.onStart();
}
// 6. Called when the fragment is no longer resumed.
@Override
public void onPause() {
super.onPause();
}
// 7. Called when the fragment is visible to the user again.
@Override
public void onResume() {
super.onResume();
}
// 8. Called when the fragment is no longer running.
@Override
public void onStop() {
super.onStop();
}
// 9. Called when the view hierarchy associated with the fragment is being removed.
@Override
public void onDestroyView() {
super.onDestroyView();
}
// 10. Called when the fragment is being destroyed.
@Override
public void onDestroy() {
super.onDestroy();
}
// 11. Called when the fragment is no longer attached to its activity.
@Override
public void onDetach() {
super.onDetach();
}
}
片段的生命周期和它所附加的宿主Activity的生命周期是相关联的。例如,当宿主Activity进入停止状态时,与之相关的所有片段也将进入停止状态,而当宿主Activity完全销毁后,所有相关片段也将随之销毁。在实际开发中,需要了解片段的生命周期,以便在不同的时间点上执行不同的操作。
提示: 为了了解Activity的生命周期,请参见Activity生命周期。
片段生命周期涵盖了片段从被创建到销毁的整个过程,以及在此过程中如何与它的宿主Activity交互。理解片段生命周期是开发Android应用程序时很重要的一点,它可以帮助我们更好地控制片段的行为,从而提高应用程序的质量。