Skip to content

(Sample 1) Quick setup & usage

Kaustubh Patange edited this page Oct 10, 2021 · 7 revisions

The sample code shows the setup of FragmentNavigator in Activity or Fragment & then navigates to FirstFragment.

class MainActivity : AppCompatActivity(), FragmentNavigator.Transmitter {
    private lateinit var navigator: FragmentNavigator

    // The host must implement FragmentNavigator.Transmitter interface so
    // that all it's child fragment get the same Navigator instance.
    override fun getNavigator(): FragmentNavigator = navigator

    override fun onCreate(savedInstanceState: Bundle?) {
        super...
        // For Fragment setup use childFragmentManager
        navigator = FragmentNavigator.with(this, savedInstanceState)
            .initialize(findViewById(R.id.container))

        // Optional navigation options to be passed
        val options = FragmentNavigator.NavOptions(
            args = FragmentFirst.Args(data = "Sample string", ...), // data class as argument.
            animation = AnimationDefinition.Fade, // supports anim, animator & androidx.transition resource types as well.
            remember = true, // Equivalent to addToBackStack.
            clearAllHistory = true, // Equivalent to popToInclusive.
        )

        // This will navigate to FirstFragment
        navigator.navigateTo(FragmentFirst::class, options)
    }

    // Override back press to check if backstack is empty & finish.
    override fun onBackPressed() {
        if (navigator.canFinish())
            super.onBackPressed()
    }
}
class FirstFragment : ValueFragment(R.layout...) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        ...
        // Check if any key arguments exist so to use further.
        if (hasKeyArgs<Args>()) {
            val args = getKeyArgs<Args>()
            Log.e(TAG, args.data)
            ...
        }

        view.toolbar.setNavigationOnClickListener {
            goBack() // Pop this fragment by calling `onBackPressed` if necessary.
        }
    }

    override fun onBackPressed(): Boolean {
        if (something-not-true) {
            ...
            return true // Back press will be suppressed when returned true.
        }
        return super.onBackPressed() // When code reaches here then back press or `goBack` call will pop this fragment.
    }

    // Type safe args. The data types that can be parceled are supported.
    @Parcelize
    data class Args(val data: String, ...) : BaseArgs()
}
Clone this wiki locally