问题
I've just begun developing android apps, so I need some help with my webview app which is easy to understand. So, this is my specific question:
How can I force a webview app to open links in it instead of open them in the default browser depending on domain?
Please enclose an edited/expanded version of this code with your answer:
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.example.com");
The domain whose content I want to open in webview is, let's say: www.qwerty.com Every other link should be open by the default browser.
Many thanks in advance.
回答1:
You'll have to create a WebViewClient
:
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
And then set it to your WebView
like this:
webview.setWebViewClient(new MyWebViewClient());
回答2:
You have to evaluate the url passed in the custom WebViewClient
.
The boolean shouldOverrideUrlLoading
has a true and a false value.
When true, you send the url to the browser, when false, you stay in the WebView
.
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.qwerty.com")) {
/*
This is my web site, so do not override;
let my WebView load the page
*/
return false;
}
/*
Otherwise, the link is not for a page on my site,
so launch another Activity that handles URLs
*/
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
Then from your Activity you call indeed the new WebClient
webview.setWebViewClient(new MyWebViewClient());
来源:https://stackoverflow.com/questions/14633367/how-can-i-force-a-webview-app-to-open-links-in-it-instead-of-open-them-in-the-de