NavHostFragment
public class NavHostFragment extends Fragment implements NavHost
DynamicNavHostFragment |
The |
NavHostFragment provides an area within your layout for self-contained navigation to occur.
NavHostFragment is intended to be used as the content area within a layout resource defining your app's chrome around it, e.g.:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_sample"
app:defaultNavHost="true" />
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"/>;
</androidx.drawerlayout.widget.DrawerLayout>
Each NavHostFragment has a NavController that defines valid navigation within the navigation host. This includes the NavGraph as well as navigation state such as current location and back stack that will be saved and restored along with the NavHostFragment itself.
NavHostFragments register their navigation controller at the root of their view subtree such that any descendant can obtain the controller instance through the Navigation helper class's methods such as Navigation.findNavController. View event listener implementations such as android.view.View.OnClickListener within navigation destination fragments can use these helpers to navigate based on user interaction without creating a tight coupling to the navigation host.
Summary
Public constructors |
|---|
Public methods |
|
|---|---|
static final @NonNull NavHostFragment |
create(@NavigationRes int graphResId, Bundle startDestinationArgs)Create a new NavHostFragment instance with an inflated NavGraph resource. |
static final @NonNull NavController |
findNavController(@NonNull Fragment fragment)Find a |
final @NonNull NavController |
The |
void |
Called when a fragment is first attached to its context. |
void |
Called to do initial creation of a fragment. |
View |
onCreateView(Called to have the fragment instantiate its user interface view. |
void |
Called when the view previously created by |
void |
@CallSuperCalled when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. |
void |
@CallSuperCalled to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. |
void |
onViewCreated(@NonNull View view, Bundle savedInstanceState)Called immediately after |
Protected methods |
|
|---|---|
@NonNull Navigator<@NonNull FragmentNavigator.Destination> |
This method is deprecated. Use {@link #onCreateNavController(NavController)} |
void |
@CallSuperThis method is deprecated. Override {@link #onCreateNavHostController(NavHostController)} to gain access to the full {@link NavHostController} that is created by this NavHostFragment. |
void |
@CallSuperCallback for when the |
Inherited methods |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Public constructors
Public methods
create
public static final @NonNull NavHostFragment create(@NavigationRes int graphResId, Bundle startDestinationArgs)
Create a new NavHostFragment instance with an inflated NavGraph resource.
| Parameters | |
|---|---|
@NavigationRes int graphResId |
Resource id of the navigation graph to inflate. |
Bundle startDestinationArgs |
Arguments to send to the start destination of the graph. |
| Returns | |
|---|---|
@NonNull NavHostFragment |
A new NavHostFragment instance. |
findNavController
public static final @NonNull NavController findNavController(@NonNull Fragment fragment)
Find a NavController given a local Fragment.
This method will locate the NavController associated with this Fragment, looking first for a NavHostFragment along the given Fragment's parent chain. If a NavController is not found, this method will look for one along this Fragment's view hierarchy as specified by Navigation.findNavController.
| Returns | |
|---|---|
@NonNull NavController |
the locally scoped |
| Throws | |
|---|---|
kotlin.IllegalStateException |
if the given Fragment does not correspond with a |
getNavController
public final @NonNull NavController getNavController()
The navigation controller for this navigation host. This method will return null until this host fragment's onCreate has been called and it has had an opportunity to restore from a previous instance state.
| Returns | |
|---|---|
@NonNull NavController |
this host's navigation controller |
| Throws | |
|---|---|
kotlin.IllegalStateException |
if called before |
onAttach
@CallSuper
public void onAttach(@NonNull Context context)
Called when a fragment is first attached to its context. onCreate will be called after this.
onCreate
@CallSuper
public void onCreate(Bundle savedInstanceState)
Called to do initial creation of a fragment. This is called after onAttach and before onCreateView.
Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the CREATED callback.
Any restored child fragments will be created before the base Fragment.onCreate method returns.
| Parameters | |
|---|---|
Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
onCreateView
public View onCreateView(
@NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
)
Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between onCreate and onViewCreated.
A default View can be returned by calling Fragment in your constructor. Otherwise, this method returns null.
It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated.
If you return a View from here, you will later be called in onDestroyView when the view is being released.
| Parameters | |
|---|---|
@NonNull LayoutInflater inflater |
The LayoutInflater object that can be used to inflate any views in the fragment, |
ViewGroup container |
If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view. |
Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
| Returns | |
|---|---|
View |
Return the View for the fragment's UI, or null. |
onDestroyView
public void onDestroyView()
Called when the view previously created by onCreateView has been detached from the fragment. The next time the fragment needs to be displayed, a new view will be created. This is called after onStop and before onDestroy. It is called regardless of whether onCreateView returned a non-null view. Internally it is called after the view's state has been saved but before it has been removed from its parent.
onInflate
@CallSuper
public void onInflate(
@NonNull Context context,
@NonNull AttributeSet attrs,
Bundle savedInstanceState
)
Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView in a layout file. Note this is before the fragment's onAttach has been called; all you should do here is parse the attributes and save them away.
This is called the first time the fragment is inflated. If it is being inflated into a new instance with saved state, this method will not be called a second time for the restored state fragment.
Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments:
public static class MyFragment extends Fragment { CharSequence mLabel; /** * Create a new instance of MyFragment that will be initialized * with the given arguments. */ static MyFragment newInstance(CharSequence label) { MyFragment f = new MyFragment(); Bundle b = new Bundle(); b.putCharSequence("label", label); f.setArguments(b); return f; } /** * Parse attributes during inflation from a view hierarchy into the * arguments we handle. */ @Override public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) { super.onInflate(context, attrs, savedInstanceState); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FragmentArguments); mLabel = a.getText(R.styleable.FragmentArguments_android_label); a.recycle(); } /** * During creation, if arguments have been supplied to the fragment * then parse those out. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { CharSequence label = args.getCharSequence("label"); if (label != null) { mLabel = label; } } } /** * Create the view for this fragment, using the arguments given to it. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)"); ViewCompat.setBackground( tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb)); return v; } }
Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:
<declare-styleable name="FragmentArguments"> <attr name="android:label" /> </declare-styleable>
The fragment can then be declared within its activity's content layout through a tag like this:
<androidx.fragment.app.FragmentContainerView class="com.example.android.supportv4.app.FragmentArgumentsSupport$MyFragment" android:id="@+id/embedded" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="1" android:label="@string/fragment_arguments_embedded" />
This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_arguments_support); if (savedInstanceState == null) { // First-time init; create fragment to embed in activity. FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment newFragment = MyFragment.newInstance("From Arguments"); ft.add(R.id.created, newFragment); ft.commit(); } }
| Parameters | |
|---|---|
@NonNull Context context |
The Activity that is inflating this fragment. |
@NonNull AttributeSet attrs |
The attributes at the tag where the fragment is being created. |
Bundle savedInstanceState |
If the fragment is being re-created from a previous saved state, this is the state. |
onSaveInstanceState
@CallSuper
public void onSaveInstanceState(@NonNull Bundle outState)
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate, onCreateView, and onViewCreated.
This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.
onViewCreated
public void onViewCreated(@NonNull View view, Bundle savedInstanceState)
Called immediately after onCreateView has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
| Parameters | |
|---|---|
@NonNull View view |
The View returned by |
Bundle savedInstanceState |
If non-null, this fragment is being re-constructed from a previous saved state as given here. |
Protected methods
protected @NonNull Navigator<@NonNull FragmentNavigator.Destination>createFragmentNavigator()
Create the FragmentNavigator that this NavHostFragment will use. By default, this uses FragmentNavigator, which replaces the entire contents of the NavHostFragment.
This is only called once in onCreate and should not be called directly by subclasses.
| Returns | |
|---|---|
@NonNull Navigator<@NonNull FragmentNavigator.Destination> |
a new instance of a FragmentNavigator |
@CallSuper
protected voidonCreateNavController(@NonNull NavController navController)
Callback for when the getNavController is created. If you support any custom destination types, their Navigator should be added here to ensure it is available before the navigation graph is inflated / set.
By default, this adds a DialogFragmentNavigator and FragmentNavigator.
This is only called once when the navController is called. This will be called in onCreate if the navController has not yet been called. This should not be called directly by subclasses.
| Parameters | |
|---|---|
@NonNull NavController navController |
The newly created |
onCreateNavHostController
@CallSuper
protected void onCreateNavHostController(@NonNull NavHostController navHostController)
Callback for when the NavHostController is created. If you support any custom destination types, their Navigator should be added here to ensure it is available before the navigation graph is inflated / set.
This provides direct access to the host specific methods available on NavHostController such as NavHostController.setOnBackPressedDispatcher.
By default, this adds a DialogFragmentNavigator and FragmentNavigator.
This is only called once when the navController is called. This will be called in onCreate if the navController has not yet been called. This should not be called directly by subclasses.
| Parameters | |
|---|---|
@NonNull NavHostController navHostController |
The newly created |