1

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

3 Answers 3

2

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorta new to this so I'm confused on where to put it I can't put it in Activity's java file because it can't extend WebViewClient because it extends AppCompatActivity... I tried putting it in a separate class but I don't know if I'm supposed to register it or something?
Create another class in your Activity's Java file and Extend there.
2

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());

Comments

0

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; } }); 

Comments