NavHostFragment

public class NavHostFragment extends Fragment implements LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, LifecycleOwner, SavedStateRegistryOwner, ActivityResultCaller, NavHost

Object
   ↳ Fragment
     ↳ NavHostFragment
Known direct subclasses
DynamicNavHostFragment

The NavHostFragment for dynamic features.


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 fields

final boolean
final @NonNull Fragment.AnimationInfo
final @NonNull Bundle
final int
final boolean
final @NonNull FragmentManager
final @NonNull ViewGroup
final int
final @NonNull ViewModelProvider.Factory
final boolean
final boolean
final int
final @NonNull FragmentManager
final boolean
final boolean
final boolean
final boolean
final @NonNull FragmentHostCallback<@NonNull ?>
final boolean
final boolean
final @NonNull LayoutInflater
final @NonNull LifecycleRegistry
final @NonNull Lifecycle.State
final boolean
final @NonNull Fragment
final boolean
final @NonNull Runnable
final @RestrictTo(value = RestrictTo.Scope.LIBRARY) @Nullable String
final boolean
final boolean
final boolean
final boolean
final @NonNull Bundle
final @NonNull SavedStateRegistryController
final @Nullable Boolean
final @NonNull Bundle
final @NonNull SparseArray<@NonNull Parcelable>
final int
final @NonNull String
final @NonNull Fragment
final int
final @NonNull String
final boolean
final @NonNull View
final @Nullable FragmentViewLifecycleOwner
final @NonNull MutableLiveData<@NonNull LifecycleOwner>
final @NonNull String
final @NonNull NavController

The navigation controller for this navigation host.

Public constructors

Public methods

@CallSuper void

Called when a fragment is first attached to its context.

@CallSuper void
onCreate(@Nullable Bundle savedInstanceState)

Called to do initial creation of a fragment.

@Nullable View
onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view.

void

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

@CallSuper void
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable 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.

@CallSuper void
onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

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

@CallSuper void

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.

void
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

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

Inherited methods

From class Fragment
void
callStartTransitionListener(boolean calledDirectly)
@NonNull FragmentContainer
void
dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable Array<@NonNull String> args
)
final @Override boolean
@Nullable Fragment
@NonNull String
final @Nullable FragmentActivity
boolean
boolean
@NonNull View
final @Nullable Bundle
final @NonNull FragmentManager
@Nullable Context
@NonNull @Override ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom {@code Factory} is provided to the ViewModelProvider constructors.

int
@Nullable Object
@NonNull SharedElementCallback
int
@Nullable Object
@NonNull SharedElementCallback
@NonNull View
final @Nullable FragmentManager

This method is deprecated. Deprecated in Java

final @Nullable Object
final int
final @NonNull LayoutInflater
@NonNull @RestrictTo(value = RestrictTo.Scope.LIBRARY_GROUP_PREFIX) LayoutInflater
getLayoutInflater(@Nullable Bundle savedFragmentState)

This method is deprecated. Deprecated in Java

@Override @NonNull Lifecycle

Returns the Lifecycle of the provider.

@NonNull LoaderManager

This method is deprecated. Deprecated in Java

int
final @Nullable Fragment
final @NonNull FragmentManager
boolean
int
int
float
@Nullable Object
final @NonNull Resources
final boolean

This method is deprecated. Deprecated in Java

@Nullable Object
final @NonNull @Override SavedStateRegistry

Returns owned SavedStateRegistry

@Nullable Object
@Nullable Object
@NonNull ArrayList<@NonNull String>
@NonNull ArrayList<@NonNull String>
final @NonNull String
getString(@StringRes int resId)
final @NonNull String
getString(@StringRes int resId, @Nullable Object formatArgs)
final @Nullable String
final @Nullable Fragment

This method is deprecated. Deprecated in Java

final int

This method is deprecated. Deprecated in Java

final @NonNull CharSequence
getText(@StringRes int resId)
boolean

This method is deprecated. Deprecated in Java

@Nullable View
@MainThread @NonNull LifecycleOwner
@NonNull LiveData<@NonNull LifecycleOwner>
@NonNull @Override ViewModelStore

Returns owned ViewModelStore

final @RestrictTo(value = RestrictTo.Scope.LIBRARY_GROUP_PREFIX) boolean
final @Override int
void
final boolean
final boolean
final boolean
final boolean
final boolean
final @RestrictTo(value = RestrictTo.Scope.LIBRARY_GROUP_PREFIX) boolean
boolean
final boolean
final boolean
final boolean
final boolean
void
@MainThread @CallSuper void
onActivityCreated(@Nullable Bundle savedInstanceState)

This method is deprecated. Deprecated in Java

void
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

This method is deprecated. Deprecated in Java

@MainThread @CallSuper void

This method is deprecated. Deprecated in Java

@MainThread void

This method is deprecated. Deprecated in Java

@Override @CallSuper void
@MainThread boolean
@MainThread @Nullable Animation
onCreateAnimation(int transit, boolean enter, int nextAnim)
@MainThread @Nullable Animator
onCreateAnimator(int transit, boolean enter, int nextAnim)
@MainThread @Override void
@MainThread void
@MainThread @CallSuper void
@MainThread void
@MainThread @CallSuper void
@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)
@MainThread void
onHiddenChanged(boolean hidden)
@UiThread @CallSuper void
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated. Deprecated in Java

@MainThread @Override @CallSuper void
void
onMultiWindowModeChanged(boolean isInMultiWindowMode)
@MainThread boolean
@MainThread void
@MainThread @CallSuper void
void
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)
@MainThread void
void
onRequestPermissionsResult(
    int requestCode,
    @NonNull Array<@NonNull String> permissions,
    @NonNull int[] grantResults
)

This method is deprecated. Deprecated in Java

@MainThread @CallSuper void
@MainThread @CallSuper void
@MainThread @CallSuper void
@MainThread @CallSuper void
onViewStateRestored(@Nullable Bundle savedInstanceState)
void
performActivityCreated(@NonNull Bundle savedInstanceState)
void
void
boolean
void
performCreate(@NonNull Bundle savedInstanceState)
boolean
performCreateOptionsMenu(
    @NonNull Menu menu,
    @NonNull MenuInflater inflater
)
void
performCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)
void
void
void
@NonNull LayoutInflater
void
void
performMultiWindowModeChanged(boolean isInMultiWindowMode)
boolean
void
void
void
performPictureInPictureModeChanged(boolean isInPictureInPictureMode)
boolean
void
void
void
void
void
void
void
final void
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)
final @MainThread @NonNull @Override ActivityResultLauncher<@NonNull I>
<I extends Object, O extends Object> registerForActivityResult(
    @NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
    @NonNull ActivityResultCallback<@NonNull O> callback
)

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

final @MainThread @NonNull @Override ActivityResultLauncher<@NonNull I>
<I extends Object, O extends Object> registerForActivityResult(
    @NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<@NonNull O> callback
)

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

void
final void
requestPermissions(
    @NonNull Array<@NonNull String> permissions,
    int requestCode
)

This method is deprecated. Deprecated in Java

final @NonNull FragmentActivity
final @NonNull Bundle
final @NonNull Context
final @NonNull FragmentManager

This method is deprecated. Deprecated in Java

final @NonNull Object
final @NonNull Fragment
final @NonNull View
void
final void
restoreViewState(@NonNull Bundle savedInstanceState)
void
void
void
setAnimations(int enter, int exit, int popEnter, int popExit)
void
void
void
void
void
void
void
setHasOptionsMenu(boolean hasMenu)
void
void
setMenuVisibility(boolean menuVisible)
void
setNextTransition(int nextTransition)
void
setPopDirection(boolean isPop)
void
void
void
setRetainInstance(boolean retain)

This method is deprecated. Deprecated in Java

void
void
void
setSharedElementNames(
    @Nullable ArrayList<@NonNull String> sharedElementSourceNames,
    @Nullable ArrayList<@NonNull String> sharedElementTargetNames
)
void
void
setTargetFragment(@Nullable Fragment fragment, int requestCode)

This method is deprecated. Deprecated in Java

void
setUserVisibleHint(boolean isVisibleToUser)

This method is deprecated. Deprecated in Java

boolean
void
void
void
startActivityForResult(@NonNull Intent intent, int requestCode)

This method is deprecated. Deprecated in Java

void
startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

This method is deprecated. Deprecated in Java

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

This method is deprecated. Deprecated in Java

void
@NonNull @Override String
void

Public fields

mAdded

@NonNull
public final boolean mAdded

mAnimationInfo

@NonNull
public final @NonNull Fragment.AnimationInfo mAnimationInfo

mArguments

@NonNull
public final @NonNull Bundle mArguments

mBackStackNesting

@NonNull
public final int mBackStackNesting

mBeingSaved

@NonNull
public final boolean mBeingSaved

mChildFragmentManager

@NonNull
public final @NonNull FragmentManager mChildFragmentManager

mContainer

@NonNull
public final @NonNull ViewGroup mContainer

mContainerId

@NonNull
public final int mContainerId

mDefaultFactory

@NonNull
public final @NonNull ViewModelProvider.Factory mDefaultFactory

mDeferStart

@NonNull
public final boolean mDeferStart

mDetached

@NonNull
public final boolean mDetached

mFragmentId

@NonNull
public final int mFragmentId

mFragmentManager

@NonNull
public final @NonNull FragmentManager mFragmentManager

mFromLayout

@NonNull
public final boolean mFromLayout

mHasMenu

@NonNull
public final boolean mHasMenu

mHidden

@NonNull
public final boolean mHidden

mHiddenChanged

@NonNull
public final boolean mHiddenChanged

mHost

@NonNull
public final @NonNull FragmentHostCallback<@NonNull ?> mHost

mInLayout

@NonNull
public final boolean mInLayout

mIsCreated

@NonNull
public final boolean mIsCreated

mLayoutInflater

@NonNull
public final @NonNull LayoutInflater mLayoutInflater

mLifecycleRegistry

@NonNull
public final @NonNull LifecycleRegistry mLifecycleRegistry

mMaxState

@NonNull
public final @NonNull Lifecycle.State mMaxState
@NonNull
public final boolean mMenuVisible

mParentFragment

@NonNull
public final @NonNull Fragment mParentFragment

mPerformedCreateView

@NonNull
public final boolean mPerformedCreateView

mPostponedDurationRunnable

@NonNull
public final @NonNull Runnable mPostponedDurationRunnable

mPreviousWho

@RestrictTo(value = RestrictTo.Scope.LIBRARY)
@Nullable
public final @RestrictTo(value = RestrictTo.Scope.LIBRARY) @Nullable String mPreviousWho

mRemoving

@NonNull
public final boolean mRemoving

mRestored

@NonNull
public final boolean mRestored

mRetainInstance

@NonNull
public final boolean mRetainInstance

mRetainInstanceChangedWhileDetached

@NonNull
public final boolean mRetainInstanceChangedWhileDetached

mSavedFragmentState

@NonNull
public final @NonNull Bundle mSavedFragmentState

mSavedStateRegistryController

@NonNull
public final @NonNull SavedStateRegistryController mSavedStateRegistryController

mSavedUserVisibleHint

@Nullable
public final @Nullable Boolean mSavedUserVisibleHint

mSavedViewRegistryState

@NonNull
public final @NonNull Bundle mSavedViewRegistryState

mSavedViewState

@NonNull
public final @NonNull SparseArray<@NonNull ParcelablemSavedViewState

mState

@NonNull
public final int mState

mTag

@NonNull
public final @NonNull String mTag

mTarget

@NonNull
public final @NonNull Fragment mTarget

mTargetRequestCode

@NonNull
public final int mTargetRequestCode

mTargetWho

@NonNull
public final @NonNull String mTargetWho

mUserVisibleHint

@NonNull
public final boolean mUserVisibleHint

mView

@NonNull
public final @NonNull View mView

mViewLifecycleOwner

@Nullable
public final @Nullable FragmentViewLifecycleOwner mViewLifecycleOwner

mViewLifecycleOwnerLiveData

@NonNull
public final @NonNull MutableLiveData<@NonNull LifecycleOwnermViewLifecycleOwnerLiveData

mWho

@NonNull
public final @NonNull String mWho
@NonNull
public final @NonNull NavController navController

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 onCreate

Public constructors

public final NavHostFragment()

Public methods

onAttach

@CallSuper
@NonNull
public @CallSuper void onAttach(@NonNull Context context)

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

onCreate

@CallSuper
@NonNull
public @CallSuper void onCreate(@Nullable 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
@Nullable Bundle savedInstanceState

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

onCreateView

@Nullable
public View onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable 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,

@Nullable 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.

@Nullable 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

@NonNull
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
@NonNull
public @CallSuper void onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable 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.

@Nullable Bundle savedInstanceState

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

onPrimaryNavigationFragmentChanged

@CallSuper
@NonNull
public @CallSuper void onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed. This can be the result of the getParentFragmentManager containing FragmentManager} having its primary navigation fragment changed via setPrimaryNavigationFragment or due to the primary navigation fragment changing in a parent FragmentManager.

Parameters
boolean isPrimaryNavigationFragment

True if and only if this Fragment and any parent fragment is set as the primary navigation fragment via setPrimaryNavigationFragment.

onSaveInstanceState

@CallSuper
@NonNull
public @CallSuper 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.

Parameters
@NonNull Bundle outState

Bundle in which to place your saved state.

onViewCreated

@NonNull
public void onViewCreated(@NonNull View view, @Nullable 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 onCreateView.

@Nullable Bundle savedInstanceState

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