Android/Kotlin - Select Current Fragment

Asked

Viewed 20 times

0

In my action I use the method onBackPressed. When will I compare the fragment that triggered the event the Id is never the same and always falls in the else. what is wrong?

override fun onBackPressed() {
    val fragment = this.supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val pressed = fragment?.childFragmentManager.fragments?.get(0) as IOnBackPressed
    var currentFragment = fragment?.childFragmentManager.fragments?.get(0)

    pressed?.onBackPressed()?.takeIf { it }?.let {

        when(currentFragment.id) {
             R.id.embalagemItemFragment -> {
                 // implemetation
             }
            else -> {
                super.onBackPressed()
            }
        }
    }
}

1 answer

0

You can use the getFragment method to catch the Fragment by means of a key in the Bundle, follows:

supportFragmentManager.getFragment()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.