将网页视图状态保存在片段中,同时更改其他片段

时间:2019-09-20 06:41:50

标签: android android-studio android-fragments android-service

我在Google上尝试了很多不同的代码,但这些代码对我都不起作用。 所以我有2个片段(带有webview),第一个片段进入youtube.com,第二个片段进入google.com

因此,当我的应用程序启动时,它从第一个fragment开始,然后当我进入第二个fragment回到第一个时,它将再次重新加载它,但我希望它应该保存其状态,并且永远不要在更改fragment时重新加载(webview)应该在用户关闭应用并重新启动时刷新。只需使用导航抽屉在片段之间切换

这是我的第一段代码

/**
 * A simple {@link Fragment} subclass.
 * created ny anshul 
 */
public class BlankFragment12 extends Fragment {

    public Handler h;
    ProgressBar progressBar;
    Bundle webViewBundle;
    public AdView adView;
    public WebView mWebView;
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWebView.restoreState(savedInstanceState);

    }
    public BlankFragment12() {
        // Required empty public constructor
    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view
                = inflater.inflate(R.layout.blank_fragment12, container, false);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        progressBar.setMax(100);
        progressBar.setProgress(1);

        mWebView = (WebView) view.findViewById(R.id.hu);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);

        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.setHorizontalScrollBarEnabled(true);
        this.mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView.loadUrl("https://youtube.com/");
        AdRequest adRequest = new AdRequest.Builder().build();
        adView = (AdView) view.findViewById(R.id.ad9View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad10View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad13View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad14View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad11View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad12View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn1);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn2);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn3);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn4);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn5);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad103);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn13);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn23);
        adView = (AdView) view.findViewById(R.id.earn33);
        adView.loadAd(adRequest);
        adView.loadAd(adRequest);
        mWebView.setOnKeyListener(new View.OnKeyListener(){

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == MotionEvent.ACTION_UP
                        && mWebView.canGoBack())
                {
                    mWebView.goBack();
                    return true;
                }
                return false;
            }

        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {


            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                mWebView.loadUrl("file:///android_asset/error.html");

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);


            }



            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                progressBar.setVisibility(View.GONE);
            }
        });
        return view;
    }

}

第二个片段的代码

/**
 * A simple {@link Fragment} subclass.
 * created by anshul
 */
public class BlankFragment2 extends Fragment {
public  Bundle webViewBundle;
    public Handler h;
    ProgressBar progressBar;
    public AdView adView;
    public WebView mWebView;
    SwipeRefreshLayout swipe;
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);



        }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWebView.restoreState(savedInstanceState);

    }


    public BlankFragment2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState ) {

        setRetainInstance(true);
        // Inflate the layout for this fragment
        View view
                = inflater.inflate(R.layout.fragment_blank_fragment3, container, false);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        progressBar.setMax(100);

        progressBar.setProgress(1);






        mWebView = (WebView) view.findViewById(R.id.hu);


        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        else {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.setHorizontalScrollBarEnabled(true);
        this.mWebView.getSettings().setDomStorageEnabled(true);


        mWebView.loadUrl("https://google.com");



        AdRequest adRequest = new AdRequest.Builder().build();
        adView = (AdView) view.findViewById(R.id.ad9View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad10View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad11View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad12View);

        adView = (AdView) view.findViewById(R.id.ad13View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad14View);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn1);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn2);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn3);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn4);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn5);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.ad103);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn13);
        adView.loadAd(adRequest);
        adView = (AdView) view.findViewById(R.id.earn23);
        adView = (AdView) view.findViewById(R.id.earn33);
        adView.loadAd(adRequest);
        adView.loadAd(adRequest);
        mWebView.setOnKeyListener(new View.OnKeyListener(){

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == MotionEvent.ACTION_UP
                        && mWebView.canGoBack())
                {
                    mWebView.goBack();
                    return true;
                }
                return false;

            }

        });    mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                mWebView.loadUrl("file:///android_asset/error.html");

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);


            }



            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                progressBar.setVisibility(View.GONE);
            }
        });
        return view;    }
}

onNavigationItemSelected代码

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            BlankFragment blankFragment = new BlankFragment();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment).commit();

        }else if (id == R.id.nav_gallery) {
            BlankFragment4 blankFragment4 = new BlankFragment4();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment4).commit();
        }
        else if (id == R.id.i) {
            BlankFragment7 blankFragment7 = new BlankFragment7();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment7).commit();
        }
        else if (id == R.id.sav) {
            BlankFragment12 blankFragment12 = new BlankFragment12();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment12).commit();
        }
        else if (id == R.id.home) {
            BlankFragment2 blankFragment2 = new BlankFragment2();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment2).commit();
        }else if (id == R.id.nav_slideshow) {
               BlankFragment3 blankFragment3 = new BlankFragment3();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment3).commit();

        } else if (id == R.id.nav_manage) {
            BlankFragment9 blankFragment9 = new BlankFragment9();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment9).commit();
        }
        else if (id == R.id.coll) {
            BlankFragment11 blankFragment11 = new BlankFragment11();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment11).commit();
        }
        else if (id == R.id.bf13) {
            BlankFragment13 blankFragment13 = new BlankFragment13();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment13).commit();
        }
        else if (id == R.id.bf14) {
            BlankFragment14 blankFragment14 = new BlankFragment14();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment14).commit();
        }
        else if (id == R.id.bf15) {
            BlankFragment15 blankFragment15 = new BlankFragment15();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment15).commit();
        }
        else if (id == R.id.fav) {
            BlankFragment10 blankFragment10 = new BlankFragment10();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment10).commit();

        } else if (id == R.id.nav_send) {
            BlankFragment8 blankFragment8 = new BlankFragment8();
            FragmentManager manager =   getSupportFragmentManager();
            manager  .beginTransaction().addToBackStack(null).replace(R.id.oou, blankFragment8).commit();
        }
        else if (id == R.id.da) {

            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=hoogle")));
        }
        else if (id == R.id.d) {

            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.hoogle.news2")));
        }
        else if (id == R.id.funny) {
            BlankFragment6 blankFragment6 = new BlankFragment6();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().addToBackStack(null).replace(R.id.oou,blankFragment6).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


}

欢迎提出更多建议,以使网页视图更流畅/更好

3 个答案:

答案 0 :(得分:0)

每次创建片段的新实例并替换旧实例时,旧实例就会被销毁。您应该使用findFragmentByTag添加/分离/显示/隐藏方法来使片段实例保持活动状态

每次分离片段时,视图都会被破坏。因此,每次附加片段时都会调用onCreateView,而每次返回片段时都会调用loadUrl

在您的onCreateView中尝试

if (savedInstanceState == null) {
   webView.loadUrl("https://google.com/")
} else {
   webView.restoreState(savedInstanceState)
}

答案 1 :(得分:0)

您可以在事务中添加片段,仅显示第一个片段,隐藏其他片段。 首先,您将必须创建Fragments的实例:

private FragmentA fragmentA;
private FragmentB fragmentB;`

onCreate的活动中:

getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, fragmentA).
                show(fragmentA).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, fragmentB).
                hide(fragmentB).commit();

现在是时候更改片段了,您可以使用以下代码:

  public void replaceFragment(int position) {
        Fragment frag;
        switch (position) {
            case 0:
                if (!(fragmentToOpen instanceof FragmentA)){
                   getSupportFragmentManager().beginTransaction().hide(fragmentToOpen)
                      .show(fragmentA).commit();
                }
                fragmentToOpen = fragmentA;
                break;
            case 1:
                if (!(fragmentToOpen instanceof FragmentB)){                    
                   getSupportFragmentManager().beginTransaction().hide(fragmentToOpen)
                      .show(fragmentB).commit();
                }
                fragmentToOpen = fragmentB;
                break;
            default:
                break;
        }
    }

答案 2 :(得分:0)

将FragmentManager设为全局,然后尝试以下代码

if (id == R.id.nav_camera) {
            FragmentTransaction transaction=  fragmentManager.beginTransaction();
             BlankFragment blankFragment = new BlankFr
            transaction.replace( R.id.contain, R.id.oou,"FragmentOne");
            transaction.addToBackStack( null);
            transaction.commit();
}

此处FragmentOne是将在您的BlankFragment中声明的标签名称。