androidkotlinandroid-architecture-navigation

android onBackPressedDispatcher not run


i want provide custom back navigation

i have this code on onCreate in Fragment:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        setHasOptionsMenu(true)

        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    Log.e("onCreate:", "back pressed invoked")
                }
            }
        )
        Log.e("onCreate: ", "Run")
    }

fragment declare :

class InsertFragment : Fragment() {

}

i using navigation component and my library version is:

def nav_version = "1.0.0"
implementation "android.arch.navigation:navigation-fragment-ktx:$nav_version"
implementation 'androidx.appcompat:appcompat:1.1.0'

when i click on back button, i have no output Log, what i missing?


Solution

  • onBackPressedDispatcher is for handle device back button.

    because of this Log only run when device back button press