SoFunction
Updated on 2025-03-11

Detailed discussion on the use and back key processing of Android WebView

Preface

webView is one of the commonly used components in Android, used to display web page content. It can load HTML files, URL links and other web content, and provide interactive functions. When using webView, we often involve back key processing. Let us discuss the use of webView and back key processing in detail below.

First, we need to add the webView component in the layout file

<WebView
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

Get webView instance in Activity and load web page content

WebView webView = findViewById();
("");

In the above code, we obtained the webView component in the layout file and loaded the specified URL link using the loadUrl() method. If you want to load the local HTML file, you can use the loadUrl("file:///android_asset/your_file.html") method.

When the webView loads a webpage, we may need to handle some events, such as opening a new webpage when clicking a link, returning to the previous page when the back key is pressed, etc. Let’s discuss the back key processing in detail below.

First, override the onKeyDown() method in Activity to listen for pressing events of the back key:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK &amp;&amp; () == KeyEvent.ACTION_DOWN) {
        // Handle back key event        return true;
    }
    return (keyCode, event);
}

In the above code, we determine whether the pressed key is a back key and whether the action of the event is pressed (ACTION_DOWN). If the condition is true, it means that the back key is pressed, and we can add our back logic where the condition is true.

In webView, we can use the goBack() method to return to the previous page. Therefore, when the back key is pressed, we can call the goBack() method of the webView to achieve the function of returning to the previous page. The specific code is as follows:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK &amp;&amp; () == KeyEvent.ACTION_DOWN) {
        if (()) {
            //If the webView can return to the previous page, call the goBack() method to return to the previous page            ();
        } else {
            // Otherwise, execute other logic (such as exiting the Activity)            finish();
        }
        return true;
    }
    return (keyCode, event);
}

In the above code, we added a judgment statement to determine whether the webView can return to the previous page. If possible, call the goBack() method of the webView to return to the previous page. If not, execute other logic (such as exiting the Activity).

In addition, we can also judge whether we can return to the previous page by listening to the history of the webView. The webView provides a WebViewClient class, which has a shouldOverrideUrlLoading() method, which can be used to listen for webView's url loading events. We can judge whether we can return to the previous page by rewriting the method and judging the history of the webView in the method. The specific code is as follows:

(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (()) {
            //If the webView can return to the previous page, call the goBack() method to return to the previous page            ();
        } else {
            // Otherwise, execute other logic (such as exiting the Activity)            finish();
        }
        return true;
    }
});

In the above code, we set a new WebViewClient instance through the setWebViewClient() method of the webView and override its shouldOverrideUrlLoading() method. In the method, we judge whether the webView can return to the previous page. If so, call the goBack() method to return to the previous page. If not, execute other logic (such as exiting the Activity).

In addition to the above code implementation method, we can also listen to the back key press event through the webView's WebChromeClient class. The WebChromeClient class has an onKeyDown() method that can be used to listen for pressing events of keyboard keys. The specific code is as follows:

(new WebChromeClient() {
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &amp;&amp; () == KeyEvent.ACTION_DOWN) {
            if (()) {
                //If the webView can return to the previous page, call the goBack() method to return to the previous page                ();
            } else {
                // Otherwise, execute other logic (such as exiting the Activity)                finish();
            }
            return true;
        }
        return (keyCode, event);
    }
});

In the above code, we set a new WebChromeClient instance through the setWebChromeClient() method of the webView and override its onKeyDown() method. In the method, we determine whether the pressed key is a back key and whether the action of the event is pressed (ACTION_DOWN). If the condition is true, it means that the back key is pressed, and we can add our back logic where the condition is true.

The above is a detailed discussion on the use of webView and back key processing. For the use of webView, we can load web page content through the loadUrl() method, and can also listen to various events of webView to achieve specific functions. For back key processing, we can rewrite the onKeyDown() method of Activity and realize the function of returning to the previous page by judging the down key event of the back key. At the same time, we can also implement back key processing by listening to the webView history or using WebChromeClient.

Attachment: Android development webview page returns to the top to close

public class MyWebViewActivity extends Activity {
     private Context context = this;
     // Bottom menu View     // public static View bottomView;
     private WebViewProgressBar webView;
     private String url;
     private HtmlBean bean;
     // Gestures     private GestureDetector mGestureDetector;
     private TextView btn_goback;
     String title;
     @Override
 protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      (savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(.usershop_layout);
      (true);
  
      url = getIntent().getStringExtra("url");
      if (!(title)) {
           TextView tv_title = (TextView) findViewById(.title_text);
           if (() &gt; 6) {
                title = (0, 6);
           }
       tv_title.setText(title);
      }
      if ((url)) {
           (this, "No relevant link address found", Toast.LENGTH_LONG).show();
           return;
      }
 
  initWebView();
  ();
  initGestureDetector();
 }
 
 // Initialize the webView private void initWebView() {
  // Bottom menu//  bottomView = findViewById(.user_bottom);
  btn_goback=(TextView)findViewById(.btn_goback);
  // WebView
  webView = (WebViewProgressBar) findViewById(.user_webview);
  // Scrollbar  (View.SCROLLBARS_OUTSIDE_OVERLAY);
  // Script support  ().setJavaScriptEnabled(true);
  // Zoom  ().setSupportZoom(true);
  (url);
 
  // WebView client  (new WebViewClient() {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String nextUrl) {
    // Next link    try {
     if(("Personal Center")){
      url=nextUrl;
     }
    } catch (Exception e) {
    }
    (nextUrl);
    return true;
   }
 
   // Start loading   @Override
   public void onPageStarted(WebView view, String url2, Bitmap favicon) {
    // TODO Auto-generated method stub
   }
 
   // Loading   @Override
   public void onPageFinished(WebView view, String url2) {
   }
  });
  btn_goback.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    finish();
   }
  });
  // Handle a gesture to handle the WebView sliding event  (new OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    return (event);
   }
  });
 }
 
 // Initialize gesture private void initGestureDetector() {
  mGestureDetector = new GestureDetector(this, new OnGestureListener() {
   @Override
   public boolean onSingleTapUp(MotionEvent e) {
    // TODO Auto-generated method stub
    return false;
   }
 
   @Override
   public void onShowPress(MotionEvent e) {
    // TODO Auto-generated method stub
 
   }
 
   @Override
   public boolean onScroll(MotionEvent e1, MotionEvent e2,
     float distanceX, float distanceY) {
    // TODO Auto-generated method stub
    return false;
   }
 
   @Override
   public void onLongPress(MotionEvent e) {
    // TODO Auto-generated method stub
 
   }
 
   @Override
   public boolean onFling(MotionEvent e1, MotionEvent e2,
     float velocityX, float velocityY) {
 
    return false;
   }
 
   @Override
   public boolean onDown(MotionEvent e) {
    // TODO Auto-generated method stub
    return false;
   }
  }, new Handler() {
 
  });
 
 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  (requestCode, resultCode, data);
  (requestCode, resultCode, data);
 
 }
 
 public void btn_on(View view){
  if(()){
   (); // goBack() means return to the Web  }else {
   finish();
  }
 }
 
 }
}

Summarize

This is the end of this article about the use of Android WebView and the processing of back keys. For more related contents of Android WebView, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!