NavHostFragment


open class NavHostFragment : Fragment, NavHost


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 companion functions

NavHostFragment
create(graphResId: @NavigationRes Int, startDestinationArgs: Bundle?)

Create a new NavHostFragment instance with an inflated NavGraph resource.

NavController

Find a NavController given a local Fragment.

Public constructors

Public functions

open Unit

Called when a fragment is first attached to its context.

open Unit
@CallSuper
onCreate(savedInstanceState: Bundle?)

Called to do initial creation of a fragment.

open View?
onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
)

Called to have the fragment instantiate its user interface view.

open Unit

Called when the view previously created by onCreateView has been detached from the fragment.

open Unit
@CallSuper
onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

open Unit

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.

open Unit
onViewCreated(view: View, savedInstanceState: Bundle?)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view.

Protected functions

open Navigator<FragmentNavigator.Destination>

This function is deprecated. Use {@link #onCreateNavController(NavController)}

open Unit

This function is deprecated. Override {@link #onCreateNavHostController(NavHostController)} to gain access to the full {@link NavHostController} that is created by this NavHostFragment.

open Unit

Callback for when the NavHostController is created.

Public properties

final NavController

The navigation controller for this navigation host.

Inherited functions

From androidx.fragment.app.Fragment
open Unit
dump(
    prefix: String,
    fd: FileDescriptor?,
    writer: PrintWriter,
    args: Array<String>?
)

Print the Fragments's state into the given stream.

final operator Boolean
equals(other: Any?)

Subclasses can not override equals().

FragmentActivity?

Return the FragmentActivity this fragment is currently associated with.

open Boolean

Returns whether the the exit transition and enter transition overlap or not.

open Boolean

Returns whether the the return transition and reenter transition overlap or not.

Bundle?

Return the arguments supplied when the fragment was instantiated, if any.

FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

open Context?

Return the Context this fragment is currently associated with.

open Any?

Returns the Transition that will be used to move Views into the initial scene.

open Any?

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

FragmentManager?

This function is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

Any?

Return the host object of this fragment.

Int

Return the identifier this fragment is known by.

LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

open LoaderManager

This function is deprecated.

Use LoaderManager.getInstance(this).

Fragment?

Returns the parent Fragment containing this Fragment.

FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

open Any?

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

Resources

Return requireActivity().getResources().

Boolean

This function is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

open Any?

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

open Any?

Returns the Transition that will be used for shared elements transferred into the content Scene.

open Any?

Return the Transition that will be used for shared elements transferred back during a pop of the back stack.

String

Return a localized string from the application's package's default string table.

String
getString(resId: @StringRes Int, vararg formatArgs: Any?)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

String?

Get the tag name of the fragment, if specified.

Fragment?

This function is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

Int

This function is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a requestKey if you need to support dynamic request keys.

CharSequence

Return a localized, styled CharSequence from the application's package's default string table.

open Boolean

This function is deprecated.

Use setMaxLifecycle instead.

open View?

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

open LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

open LiveData<LifecycleOwner>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

final Int

Subclasses can not override hashCode().

Boolean

Return true if the fragment is currently added to its activity.

Boolean

Return true if the fragment has been explicitly detached from the UI.

Boolean

Return true if the fragment has been hidden.

Boolean

Return true if the layout is included as part of an activity view hierarchy via the tag.

Boolean

Return true if this fragment is currently being removed from its activity.

Boolean

Return true if the fragment is in the resumed state.

Boolean

Returns true if this fragment is added and its state has already been saved by its host.

Boolean

Return true if the fragment is currently visible to the user.

open Unit

This function is deprecated.

use onViewCreated for code touching the view created by onCreateView and onCreate for other initialization.

open Unit
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

open Unit

This function is deprecated.

See onAttach.

open Unit

This function is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

open Unit
open Boolean

This hook is called whenever an item in a context menu is selected.

open Animation?
@MainThread
onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animation.

open Animator?
@MainThread
onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animator.

open Unit
@MainThread
onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
)

Called when a context menu for the view is about to be shown.

open Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

open Unit

Called when the fragment is no longer in use.

open Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

open Unit

Called when the fragment is no longer attached to its activity.

open LayoutInflater
onGetLayoutInflater(savedInstanceState: Bundle?)

Returns the LayoutInflater used to inflate Views of this Fragment.

open Unit

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed.

open Unit
@UiThread
@CallSuper
onInflate(
    activity: Activity,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

This function is deprecated.

See onInflate.

open Unit
open Unit
onMultiWindowModeChanged(isInMultiWindowMode: Boolean)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

open Boolean

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

open Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

open Unit

Called when the Fragment is no longer resumed.

open Unit
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

Called by the system when the activity changes to and from picture-in-picture mode.

open Unit

This function is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

open Unit
@MainThread
onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
)

Callback for when the primary navigation state of this Fragment has changed.

open Unit
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray
)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

open Unit

Called when the fragment is visible to the user and actively running.

open Unit

Called when the Fragment is visible to the user.

open Unit

Called when the Fragment is no longer started.

open Unit

Called when all saved state has been restored into the view hierarchy of the fragment.

open Unit

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

Unit
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

final ActivityResultLauncher<I>
@MainThread
<I : Any, O : Any> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    callback: ActivityResultCallback<O>
)

Register a request to start an activity for result, designated by the given contract.

final ActivityResultLauncher<I>
@MainThread
<I : Any, O : Any> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    registry: ActivityResultRegistry,
    callback: ActivityResultCallback<O>
)

Register a request to start an activity for result, designated by the given contract.

open Unit

Registers a context menu to be shown for the given view (multiple views can show the context menu).

Unit
requestPermissions(permissions: Array<String>, requestCode: Int)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Bundle

Return the arguments supplied when the fragment was instantiated.

Context

Return the Context this fragment is currently associated with.

FragmentManager

This function is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

Any

Return the host object of this fragment.

Fragment

Returns the parent Fragment containing this Fragment.

View

Get the root view for the fragment's layout (the one returned by onCreateView).

open Unit

Sets whether the the exit transition and enter transition overlap or not.

open Unit

Sets whether the the return transition and reenter transition overlap or not.

open Unit

Supply the construction arguments for this fragment.

open Unit

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

open Unit
setEnterTransition(transition: Any?)

Sets the Transition that will be used to move Views into the initial scene.

open Unit

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

open Unit
setExitTransition(transition: Any?)

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

open Unit

This function is deprecated.

This method is no longer needed when using a MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

open Unit

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

open Unit
setMenuVisibility(menuVisible: Boolean)

Set a hint for whether this fragment's menu should be visible.

open Unit
setReenterTransition(transition: Any?)

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

open Unit

This function is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

open Unit
setReturnTransition(transition: Any?)

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

open Unit

Sets the Transition that will be used for shared elements transferred into the content Scene.

open Unit

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

open Unit
setTargetFragment(fragment: Fragment?, requestCode: Int)

This function is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a requestKey using its parent fragment manager.

open Unit
setUserVisibleHint(isVisibleToUser: Boolean)

This function is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

open Boolean

Gets whether you should show UI with rationale before requesting a permission.

open Unit

Call startActivity from the fragment's containing Activity.

open Unit
startActivity(intent: Intent, options: Bundle?)

Call startActivity from the fragment's containing Activity.

open Unit
startActivityForResult(intent: Intent, requestCode: Int)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

open Unit
startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

open Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)

This function is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

open Unit

Begin postponed transitions after postponeEnterTransition was called.

open String
open Unit

Prevents a context menu to be shown for the given view.

Inherited properties

From androidx.fragment.app.Fragment
open CreationExtras

The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.

open ViewModelProvider.Factory
open Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

final SavedStateRegistry
open ViewModelStore

Returns the ViewModelStore associated with this Fragment

Public companion functions

create

Added in 2.4.0
fun create(graphResId: @NavigationRes Int, startDestinationArgs: Bundle? = null): NavHostFragment

Create a new NavHostFragment instance with an inflated NavGraph resource.

Parameters
graphResId: @NavigationRes Int

Resource id of the navigation graph to inflate.

startDestinationArgs: Bundle? = null

Arguments to send to the start destination of the graph.

Returns
NavHostFragment

A new NavHostFragment instance.

findNavController

Added in 2.4.0
fun findNavController(fragment: Fragment): NavController

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.

Parameters
fragment: Fragment

the locally scoped Fragment for navigation

Returns
NavController

the locally scoped NavController for navigating from this Fragment

Throws
kotlin.IllegalStateException

if the given Fragment does not correspond with a NavHost or is not within a NavHost.

Public constructors

Added in 1.0.0
NavHostFragment()

Public functions

onAttach

@CallSuper
open fun onAttach(context: Context): Unit

Called when a fragment is first attached to its context. onCreate will be called after this.

onCreate

@CallSuper
open fun onCreate(savedInstanceState: Bundle?): Unit

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
savedInstanceState: Bundle?

If the fragment is being re-created from a previous saved state, this is the state.

onCreateView

open fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View?

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
inflater: LayoutInflater

The LayoutInflater object that can be used to inflate any views in the fragment,

container: ViewGroup?

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.

savedInstanceState: Bundle?

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

open fun onDestroyView(): Unit

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
open fun onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
): Unit

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
context: Context

The Activity that is inflating this fragment.

attrs: AttributeSet

The attributes at the tag where the fragment is being created.

savedInstanceState: Bundle?

If the fragment is being re-created from a previous saved state, this is the state.

onSaveInstanceState

@CallSuper
open fun onSaveInstanceState(outState: Bundle): Unit

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.

Parameters
outState: Bundle

Bundle in which to place your saved state.

onViewCreated

open fun onViewCreated(view: View, savedInstanceState: Bundle?): Unit

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
view: View

The View returned by onCreateView.

savedInstanceState: Bundle?

If non-null, this fragment is being re-constructed from a previous saved state as given here.

Protected functions

createFragmentNavigator

Added in 1.0.0
Deprecated in 2.1.0
protected open fun createFragmentNavigator(): Navigator<FragmentNavigator.Destination>

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
Navigator<FragmentNavigator.Destination>

a new instance of a FragmentNavigator

onCreateNavController

Added in 2.1.0
Deprecated in 2.4.0
@CallSuper
protected open fun onCreateNavController(navController: NavController): Unit

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
navController: NavController

The newly created NavController.

onCreateNavHostController

Added in 2.4.0
@CallSuper
protected open fun onCreateNavHostController(navHostController: NavHostController): Unit

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
navHostController: NavHostController

The newly created NavHostController that will be returned by getNavController after

Public properties

Added in 1.0.0
final val navControllerNavController

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
NavController

this host's navigation controller

Throws
kotlin.IllegalStateException

if called before onCreate