代码之家  ›  专栏  ›  技术社区  ›  Shlomi Schwartz

Android-还原片段WebView状态以避免重新加载

  •  1
  • Shlomi Schwartz  · 技术社区  · 6 年前

    我有一个底部导航栏应用程序(用Android Studio模板创建)。应用程序在两个片段之间导航。在其中一个片段上,我有一个WebView,我希望避免每次导航到片段视图时都重新加载它。

    阅读后 this article ,我尝试保存webview状态如下:

    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);
        }
    
    }
    

    为空 然后重新加载HTML。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Emre Dalkiran    6 年前

    因为 Fragment Activity 的生命周期。 碎片 onPause() onResume() 只有在 活动 它的生命周期已经转到了那个状态。

    看一看 this solution , fragment life cycle communications life cycle

    编辑

    1. 首先尝试将片段添加到后堆栈。
    2. 暂停()
    3. 而不是试图恢复 onCreateView onActivityCreated() 方法。

    编辑-2

    暂停() 能接到电话。