Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onBackPressed handling with new Navigation component

I need some suggestions;

I'm experimenting with Navigation library. I have a fragment which has a webView. I want to check if it canGoBack and do so if it can, otherwise not interfere.

1. Interface approach: Since Navigation is handling transactions, I don't create an instance of my fragment manually anymore, which I can assign as a listener in activity.

1. Key listening: I really think it looks ugly and I don't think it's a generic solution, so I skip this one.

I need some opinions on how can it be done with Navigation library. When you try to get currentDestination from navController, it's NavigationDestination object which provides information about current fragment, such as label given in xml.

When I inspect fragmentManager, I see that backStack is empty & fragment transaction took place without a tag.

IMHO it wouldn't fit the concept of the library to do findFragment kind of operations to somewhat interact with current fragment, but I can't seem to find a way through with it at the moment. Any suggestions ?

like image 707
Mel Avatar asked May 17 '18 14:05

Mel


People also ask

How do I navigate from one page to another in Android?

There isn't a DIRECT page navigation code , but instead there is a start Activity . By starting an activity you are able to go to another page because the page is related to the activity. Intent myIntent = new Intent(Enter_Your_Current_Activity. this, Enter_The_Activity_You_Want_To_Navigate_To.

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }


2 Answers

I found a way to do it as before with interface or base fragment class.

in Activity:

override fun onBackPressed() {
    val f = currentFragment
    if (f !is BaseFragment || f.onBackPressed()) {
        if (!findNavController(R.id.nav_host_fragment).navigateUp()) {
            super.onBackPressed()
        }
    }
}

val currentFragment: Fragment?
    get() = nav_host_fragment.childFragmentManager.findFragmentById(R.id.nav_host_fragment)

in BaseFragment:

open fun onBackPressed() = true /*or false if you want to prevent navigation*/
like image 184
AnoDest Avatar answered Sep 27 '22 19:09

AnoDest


We can directly handle OnBackPressed from any fragment

requireActivity().onBackPressedDispatcher
        .addCallback(viewLifecycleOwner, object: OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            //Handle back event from any fragment 
        }
    })

Put above code in onViewCreated

like image 39
Kalpesh Kulye Avatar answered Sep 27 '22 19:09

Kalpesh Kulye