Issue
I have a bottom navigation bar app (created with an Android Studio template). The app navigates between two fragments. On one of the fragments, I have a WebView and I want to avoid it being reloaded each time I navigate to the fragment view.
After reading this article, I've tried saving the webview state like so:
package com.example.bla.myapp.fragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.example.shlomishwartz.adintegration.R;
public class VideoFragment extends Fragment {
private String PAGE_URL = "https://my.html.view.html";
private Bundle webViewBundle;
private WebView webView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View videoFragment = inflater.inflate(R.layout.video_fragment, null);
webView = (WebView) videoFragment.findViewById(R.id.video_webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebView.setWebContentsDebuggingEnabled(true);
webView.setWebViewClient(new WebViewClient());
// HERE IS WHERE I TRY TO RESTORE THE STATE
if (webViewBundle == null) {
webView.loadUrl(PAGE_URL);
} else {
webView.restoreState(webViewBundle);
}
return videoFragment;
}
@Override
public void onPause() {
// HERE IS WHERE I SAVE THE STATE
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
}
However, each time I navigate to the fragment webViewBundle is null and the HTML is reloaded.
What am I missing?
Solution
Because a Fragment
's life cycle is strictly related to its Activity
's life cycle. Fragment
methods like onPause()
and onResume()
only get called if Activity
's life cycle has switched to that states.
Have a look at this solution, fragment life cycle communications and life cycle documentations.
Edit
- First try adding your fragment to back stack.
- Your
onPause()
method is probably useless at the moment unless when you change your activity while in your fragment. - Instead of trying restoring within
onCreateView
method, try to restore your state from instance variables withinonActivityCreated()
method.
Edit-2
Apparently the first part of this answer is not %100 correct. There may be some cases when fragment transaction occurs, methods like onPause()
can get called.
Answered By - Emre Dalkiran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.