startActivityForResult
but for fragments! (Addon for Jetpack's Navigation component).
🗒 You can read a blog post about this library from here.
- Add NavigationResult's dependency into your
build.gradle
file:
dependencies {
implementation "com.phelat:navigationresult:[latest_version]"
}
- Extend your starting point fragment from
BundleFragment
class FragmentA : BundleFragment() {
...
}
- Navigate to destination fragment using
navigate
function:
navigate(FragmentADirections.fragmentAToFragmentB(), REQUEST_CODE)
// If you aren't using SafeArgs plugin, you can navigate with direction id
navigate(R.id.fragmentAToFragmentB, REQUEST_CODE)
- Override
onFragmentResult
in your starting point fragment:
class FragmentA : BundleFragment() {
override fun onFragmentResult(requestCode: Int, bundle: Bundle) {
// Do whatever you want with result bundle from the destination fragment
}
}
- In your destination fragment use
navigateUp
extension function:
navigateUp(REQUEST_CODE, Bundle().apply {
putBoolean("isLoginSuccessful", true)
})
- Extend your activity from
FragmentResultActivity
:
class MainActivity : FragmentResultActivity() {
// Return the id of your NavHostFragment
override fun getNavHostFragmentId(): Int = R.id.nav_host_fragment
}
- You can pass request code through
navigate
function:
navigate(FragmentADirections.fragmentAToFragmentB(), REQUEST_CODE)
// OR
navigate(R.id.fragmentAToFragmentB, REQUEST_CODE)
- You can also set request code in your navigation graph xml file:
<fragment
android:id="@+id/fragment_a"
android:name="com.sample.FragmentA">
<action
android:id="@+id/a_to_b"
app:destination="@id/fragment_b">
<argument
android:name="fragment:requestCode"
android:defaultValue="1000"
app:argType="integer" />
</action>
</fragment>
If you don't want to set default value for fragment:requestCode
:
navigate(FragmentADirections.fragmentAToFragmentB(10000))
// OR
navigate(R.id.fragmentAToFragmentB, Bundle().apply {
putInt("fragment:requestCode", 1000)
})
You can update NavHostFragment's id at runtime using updateNavHostFragmentId
function:
// This function is only available for FragmentResultActivity
updateNavHostFragmentId(R.id.anotherNavHostFragment)
You can navigate with request code from FragmentResultActivity as you would do using BundleFragment.
This library does support <dialog/>
destinations and you can use them normally without doing anything extra.
You can checkout the sample project for NavigationResult from here