DevDengChao
DevDengChao

Reputation: 308

How to go back with WebView inside Fragment controlled by NavHostFragment?

Current situation:

What troubles me:

I can forward web pages inside WebView, but when I press back to go back inside the WebView, the NavController handle's it, pop the fragment away. Since the WebView is inside a fragment not an activity, which means there is not method called onBackPressed() to override.

Reference:

Upvotes: 0

Views: 1219

Answers (4)

ud_an
ud_an

Reputation: 4921

code lab has example https://codelabs.developers.google.com/handling-gesture-back-navigation#5 you need onBackPressedDispatcher which need to be enabled and disabled.

Upvotes: 0

apksherlock
apksherlock

Reputation: 8371

As far as I understand, you need a way to handle onBackPressed on your fragment, right? With NavigationComponent you can do it like this, in your onViewCreated:

 requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
              if (mWebView.canGoBack()) {
                mWebView.goBack();
             } else {
               findNavController().popBackStack(R.id.dest, false)
             }
            }
        })

Upvotes: 2

d-feverx
d-feverx

Reputation: 1672

add a new fragment and inside that place your WebView ,using navigation editor navigate from WebViewFragment to new fragment ,in the right hand side of navigation editor you can see an option to backstack option to manage .

Upvotes: 0

Ashwin Jawale
Ashwin Jawale

Reputation: 15

you can use mWeb.goBack(); to goBack to the previous page or for returning back.

Upvotes: -1

Related Questions