I have a Fragment with ViewPager inside it, which contains 3 tabs. I have used Jetpack navigation to handle navigation. In the first tab I have a Fragment with WebView, as per native behaviour of Jetpack navigation, it recreates view every time we navigate to another fragment.

Here is the problem, it loads the URL every time when I navigate back to the WebView Fragment. That can't be handled using live data.

I have tried to cache Webview content, but it is just makes loading faster but it's not immediate.

here is my code snippet

MyFragment.kt

class MyFragment : BaseViewModelFragment<MyViewModel>(), View.OnClickListener {
    override fun getContentResource(): Int = R.layout.fragment_my
    override fun buildViewModel(): MyViewModel {
        return ViewModelProviders.of(this, viewModelFactory)[MyViewModel::class.java]
    }

    override fun initLiveDataObservers() {
        super.initLiveDataObservers()
    }

    override fun initViews() {
        super.initViews()
        setupWebView()
    }

    private fun setupWebView() = with(webView) {
        settings.domStorageEnabled = true
        settings.setAppCachePath("/data/data/" + activity?.packageName + "/cache")
        settings.setAppCacheEnabled(true)
        settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        webViewClient = MyWebviewClient()
        webChromeClient = MyChromeClient()
        loadUrl("http://google.com")
    }
}

Any help would be appriated, thanks in advance!

1 Answers

2
Maddy On Best Solutions

I fixed it by adding WebView run time

class MyFragment : BaseViewModelFragment<MyViewModel>(), View.OnClickListener {

    private val myWebview by lazy {
        WebView(requireContext().applicationContext).apply {
            webViewClient = MyWebviewClient()
            webChromeClient = MyChromeClient()
        }
    }

    override fun getContentResource(): Int = R.layout.fragment_home

    override fun buildViewModel(): MyViewModel {
        return ViewModelProviders.of(this, viewModelFactory)[MyViewModel::class.java]
    }

    override fun initLiveDataObservers() {
        super.initLiveDataObservers()
    }

    override fun initViews() {
        super.initViews()
        container.addView(myWebview, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        )
    }

    override fun onDestroyView() {
        (myWebview.parent as ViewGroup).removeView(myWebview)
        super.onDestroyView()
    }
}