2

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.

2 Answers 2

6

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

3 Comments

WOW!!! Thank you for the very fast answer! But: Where do I have to input the domain, in my case www.qwerty.com?
You don't need to put in a domain. The WebViewClient will override every domain.
But now every link opens in webview. That's not what I wanted. Only links with the domain name "www.querty.com" should open in webview... Can you help me, please?
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()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.