Solution to Android Webview Redirection Problem

  • 2021-09-05 00:59:47
  • OfStack

webview redirection is required in the project, but since there are many load operations in an webveiw, webview is being called. goback () method, it often does not achieve the operation effect we need.

1. Solutions

WebBackForwardList webBackForwardList = webview. copyBackForwardList () Gets the webview load stack and then does the logical operation on the load stack

2. Common methods of webBackForwardList


int size = webBackForwardList.getSize()
webBackForwardList.getCurrentItem()
webBackForwardList.getCurrentIndex()
webBackForwardList.getItemAtIndex(index)

The getsize () method gets the length of the current load stack;

getCurrentItem () obtains the interface loaded by webview at present, and we can obtain url, title and other contents under this method;

getCurrentIndex () gets the location of the current load in the load stack;

webBackForwardList. getItemAtIndex (index) gets the index page in the loading stack;

3. Reasonable use

In 2 we get 1 bit of information to load the page, and then we can use the current url, title, location. To carry out corresponding processing.

4. Use of Demo

Now we have such a scenario: open an activity, webview loads A interface, and then the user clicks B in A, then C and D. To return to the operation, we need to skip from D to B, and then skip A. Here's the code:


public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (webView.canGoBack()) {
      WebBackForwardList webBackForwardList = webView.copyBackForwardList();
      if (webBackForwardList.getCurrentIndex() == 4) {// Currently in D Interface 
        webView.loadUrl(webBackForwardList.getItemAtIndex(1).getUrl());// Pick and turn to B Interface 
        return true;
      }
      webView.goBack();
    }    
    return true;
  }

Related articles: