当前位置: 首页 > 工具软件 > Android Angle > 使用案例 >

Fragment for Android

汤英豪
2023-12-01

As an android development, I think you have been familiar with Fragment. It is a piece of an application’s user interface. It can has its own behavior. It must be placed in an Activity.

Interaction with fragments is done through FragmentManager,which can be obtained via Activity#getFragmentManager() or Fragment#getFragmentManager() . In androidx.fragment.app static library, your activity must extend FragmentActivity. So FragmentManager can be obtained via FragmentActivity#getSupportFragmentManager.

Please Note:
A fragment is closely tied to the Activity where it is in, and can not be used apart from one.Even though fragment defines its own lifecycle,but that lifecycle is dependent on its activity:
(1)if the activity is stopped , no fragments instead of it can be started.
(2)if the activity is destroyed, all fragments will destroyed.

Let’s discuss the lifecycle of fragment. As mentioned above, its lifecycle is dependent on its activity.

Lifecycle

  1. onAttach: called once the fragment is associated with its activity.
  2. onCreate: called to do initial creation of the fragment.
  3. onCreateView: creates and returns the view hierarchy associated with the fragment
  4. onActivityCreated:tells the fragment that its activity has completed its own Activity#onCreate
  5. onViewStateRestored: tells the fragment that all of the saved state of its view hierachy has been restored.
  6. onStart:makes the fragment visible to the user . This is based on its activity being started.
  7. onResume: makes the fragment begin interacting with the user. This is based on its activity being resumed.
  8. onPause: fragment is no longer interacting with the user. Because its activity is being paused.
  9. onStop:fragment is no longer visible to the user. Becuase its activity is being stopped.
  10. onDestroyView : allows the fragment to clean up its resources associated with its view.
  11. onDestroy:called to do final cleanup of the fragment’s state.
  12. onDetach:called immediately prior to the fragment no longer being associated with its activity.

In our development, we can make full use of the lifecycle of fragment.

Tag & ID

The fragment being instantiated must have some kind of identifier so that it can be re-associated with a previous instance if the parent activity neesds to be destroyed and recreated.
(1)android:tag in xml layout can be used in fragment to provide a specific tag name for the fragment
(2)android:id in xml layou can be used in fragment to provide a specific identifier for the fragment.

BackStack

The transaction in which fragments are modified can be placed on an internal back-stack of the owing activity.When the user presses back in the activity, any transaction on the back stack is popped off before the activity itself is finished.
Only one FragmentManager is allowed to control the fragment back stack at any given time.

 类似资料:

相关阅读

相关文章

相关问答