How to add “Go Back” function in WebView inside Fragment?

前端 未结 13 2035
余生分开走
余生分开走 2020-11-27 05:21

UPDATE: Solved! Problem was related to my Viewpager not WebView.

I\'m trying to add a \"Go Back\" function to my WebView which is insid

相关标签:
13条回答
  • 2020-11-27 05:25

    you can do this by :

    • in the Activity put :

      // Set WebView
      
      public void setWebView(WebView web) {
      
          this.web = web;
      }
      
    • in the web fragment after ActivityCreated() put:

      ((Your_Activity) getActivity()).setWebView(webView);

    • Don't forget to set webView from the onCreateView() like these:

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
          webView = (WebView) inflater.inflate(R.layout.your_web_fragment, container,
                  false);
          return web;
      }
      
    0 讨论(0)
  • 2020-11-27 05:26

    @OmidAmnivia answer is correct your app the solution to the crash is

    @Override
    public void onBackPressed() {
    if(webFragment.isInitialized && webFragment.canGoBack()){
        webFragment.goBack();
    }else{
        super.onBackPressed();
    }
    }
    

    You have to check whether your class has been initialised or not.

    0 讨论(0)
  • 2020-11-27 05:26

    This worked in my case

    public class FantasyFragment extends Fragment  implements SwipeRefreshLayout.OnRefreshListener {
    
    WebView webview;
    SwipeRefreshLayout swipeLayout;
    String currentUrl="https://www.stackoverflow.com/";
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_stadium, container, false);
    
    
        swipeLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipescreen);
        swipeLayout.setOnRefreshListener(this);
    
        return root;
    }
    
    @Override
    public void onStart() {
        super.onStart();
        LoadWeb();
    }
    
    public void LoadWeb() {
    
    
    
        webview = (WebView) getActivity().findViewById(R.id.webview786);
        swipeLayout.setRefreshing(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webview.getSettings().setAppCacheEnabled(true);
    
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
    
        webSettings.setDatabaseEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setEnableSmoothTransition(true);
    
        webview.loadUrl(currentUrl);
    
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Snackbar.make(view, "Connection Error", Snackbar.LENGTH_LONG)
                        .setAction("Retry", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                LoadWeb();
                            }
                        }).show();
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                swipeLayout.setRefreshing(false);
                currentUrl = url;
                super.onPageFinished(view, url);
            }
        });
    
        webview.canGoBack();
        webview.setOnKeyListener(new View.OnKeyListener() {
    
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == MotionEvent.ACTION_UP
                        && webview.canGoBack()) {
                    webview.goBack();
                    return true;
                }
                return false;
            }
        });
    }
    @Override
    public void onRefresh() {
        LoadWeb();
    }
    }
    
    0 讨论(0)
  • 2020-11-27 05:28

    Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:

    1. Override the onBackPressed inside the activity.
    2. When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
    3. If it is, ask the fragment if the webview can go back.
    4. if it is not, call the super or whatever you need

    Edit:

     @Override
     public void onBackPressed() {
           Fragment webview = getSupportFragmentManager().findFragmentByTag("webview");
           if (webview instanceof MyWebViewFragment) {
                  boolean goback = ((MyWebViewFragment)webview).canGoBack();
                  if (!goback)
                    super.onBackPressed();
           }
     }
    
    0 讨论(0)
  • 2020-11-27 05:29

    @RomanBlack's answer gave me the right idea, but since we use kotlin I had to adapt the answer a little bit.

    webView.setOnKeyListener { _, _, keyEvent ->
            if (keyEvent.keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
                false
            } else if (keyEvent.keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == MotionEvent.ACTION_UP) {
                webView.goBack()
                true
            } else true
        }
    

    if you want to do it with returns you have to add something like:

    return@setOnKeyListener true
    
    0 讨论(0)
  • 2020-11-27 05:31

    Perhaps its android restriction. Try to do this using handler.

    public final class TestFragment extends Fragment {
    
    
        static WebView mWeb;
        private View mContentView;
    
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message message) {
                switch (message.what) {
                    case 1:{
                        webViewGoBack();
                    }break;
                }
            }
        };
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {   
    
            mContentView = inflater.inflate(R.layout.webview, null);
            mWeb = (WebView)mContentView.findViewById(R.id.webview);
    
            WebSettings settings = mWeb.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setSupportZoom(false);
            mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            mWeb.getSettings().setBuiltInZoomControls(false);
            mWeb.loadUrl("myurl...");
            mWeb.setOnKeyListener(new OnKeyListener(){
    
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK 
                            && event.getAction() == MotionEvent.ACTION_UP 
                            && mWeb.canGoBack()) {
                        handler.sendEmptyMessage(1);
                        return true;
                    }
    
                    return false;
                }
    
            });
    
        }   
    
        private void webViewGoBack(){
            mWeb.goBack();
        }
    }
    
    0 讨论(0)
提交回复
热议问题