Reputation:
I am coding an Android app in Android Studio, I have an Activity with a WebView and would like to know if there is a way to detect a hyperlink a user clicks in the WebView
I want to be able to detect if the link is link1.com it will continue and open like normal but if its link2.com it cancels and opens another activity
Upvotes: 1
Views: 94
Reputation: 2819
For what you need, you have to use a WebViewClient
like this:
WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("link2.com")){//if url contains link2.com open new activity
startactivity(new Intent(CurrentActivity.this, SecondActivity.class)); //replace CurrentActivity with the activity where you are writing this code and SecondActivty with the activity you want to open
}
else {
//do nothing, webview will load that link
}
return true;
}
});
Upvotes: 0
Reputation: 510
do as answered by Faizal Abbas.Create a class extending WebViewClient,override the method shouldOverrideUrlLoading(),then set the WebViewClient to your webview.
WebView webView=yourWevView; webView.setWebViewClient(new MyWebViewClient());
Upvotes: 2
Reputation: 205
Use this to Check the url and perform your task
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equals(link2)){
Intent i = new Intent (Youractivityname.this, SecondActivity.class);
startactivity(i);
}
return true;
}
}
Upvotes: 2