Thursday, 16 May 2019

Android Navigation Component keeps reloading WebView

Today I faced a problem with WebView inside a Fragment using Android Navigation Component. In my case, in Fragment1 there is button under WebView. User needs to scroll down to click it. After clicking it, a new destination is opened (Fragment2). Then, when user goes back to Fragment1, WebView is reloaded, and viewport is scrolled to the top again.

It's extremely annoying. User might been scrolling down for minutes, and it always throws him to the very top after coming back. Can I somehow prevent it from reloading / scrolling back to top?

Example code could be as simple as that:

class Fragment1 : Fragment() {

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    webView.loadData(getString(R.string.some_very_long_html), "text/html", "UTF-8")
    buttonBelowWebView.setOnClickListener {
      navigateToFragment2()
    }
  }

}

If WebView contains videos, loading might take even up to 5 seconds. It's terrible experience.

I tried adding flag to load only one time, but then WebView is empty when navigating back from Fragment2:

class Fragment1 : Fragment() {

  var loaded = false
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    if(!loaded) {
      webView.loadData(getString(R.string.some_very_long_html), "text/html", "UTF-8")
      loaded = true
    }
  }

}

Note that in real life I use ViewModels and observe data from rest api, but the problem stays the same.

Also, example code I provided is written in Kotlin, but if there is solution in Java, then it's appreciated too.

Is it possible to not reload WebView and reset scroll position when navigating back from nested destination?



from Android Navigation Component keeps reloading WebView

No comments:

Post a Comment