Nurseyit Tursunkulov
Nurseyit Tursunkulov

Reputation: 9380

navigate without view jetpack

I want to override onbackpressed(). onBackPressed() shoud navigate to home fragment. But for navigation I need view, which I don't have. How to do this?

    override fun onBackPressed() {
    findNavController(*/here it shows error/*).navigate(R.id.action_global_postsHolderFragment)
}

Upvotes: 0

Views: 261

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199825

As per the Navigate to a destination documentation, there are findNavController methods that are suitable for a View, Fragment, or Activity.

Assuming your NavHostFragment has an android:id="@+id/nav_host" and that you have included the -ktx artifacts in your build.gradle, you could use:

override fun onBackPressed() {
    findNavController(R.id.nav_host).navigate(R.id.action_global_postsHolderFragment)
}

Upvotes: 1

Related Questions