Android webview open new tab
To open a new tab in an Android WebView, you can use the shouldOverrideUrlLoading
method and return true
to indicate that the WebView should not load the URL in the current tab, but instead open a new tab.
Here is an example:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
This code sets a WebViewClient
on the WebView and overrides the shouldOverrideUrlLoading
method. When the WebView is about to load a URL, this method is called. If the method returns true
, the WebView will not load the URL in the current tab, but instead open a new tab.
You can also use the openFileChooser
method to open a new tab:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.openFileChooser(new WebViewClient.OpenFileChooserCallback() {
@Override
public void openFileChooser(ValueCallback<Uri> valueCallback) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
return true;
}
});
This code uses the openFileChooser
method to open a new tab when the WebView is about to load a URL. The openFileChooser
method takes a ValueCallback
as a parameter, which is called when the user selects a file to open. In this case, we create an Intent
to open the URL in a new tab and start the activity.
You can also use the WebView.setWebChromeClient
method to open a new tab:
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean userGesture, Message resultMsg) {
WebView newWebView = new WebView(view.getContext());
newWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
view.addView(newWebView);
return true;
}
});
This code sets a WebChromeClient
on the WebView and overrides the onCreateWindow
method. When the WebView is about to create a new window, this method is called. We create a new WebView and set it as the content view of the new window. We also set a WebViewClient
on the new WebView to handle the URL loading.
Note that the above examples are just a few ways to open a new tab in an Android WebView. The exact implementation may vary depending on your specific requirements and the version of Android you are targeting.