As you know you can have one activity but different fragments embedded in it. That is why fragment lifecycle is also important for developers.
On the diagram below you can see how Android fragment lifecycle looks like:
As described in the official Android documentation you should implement at least below three methods:
OnCreate - the system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
OnCreateView - The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
OnPause - The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).
Here is sample implementation in Xamarin.Android:
public class MainFragment : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
// You should initialize essential components of the fragment
// that you want to retain when the fragment is paused or stopped, then resumed.
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// The system calls this when it's time for the fragment to draw its user interface for the first time.
var mainView = inflater.Inflate(Resource.Layout.MainFragment, container, false);
return mainView;
}
public override void OnPause()
{
// The system calls this method as the first indication that the user is leaving the fragment
base.OnPause();
}
}
Of course you can add additional methods here if you want to handle different states.