Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open new browser from WebViewClient?

Short question that i cannot get my finger on, i'd like to launch a new browser from my WebView after people click a hyperlink. But how can i set that target of that link to escape the WebViewClient??

Here's my code, any help is greatly appreciated:

WebView site = (WebView)findViewById(R.id.WebView);
  site.setWebViewClient(new WebViewClient());
  site.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
  site.getSettings().setJavaScriptEnabled(true);

  button1.setOnClickListener(button1OnClickListener);
  button2.setOnClickListener(button2OnClickListener);
  button3.setOnClickListener(button3OnClickListener);
  button4.setOnClickListener(button4OnClickListener);


  final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

  progressBar = ProgressDialog.show(FlitsersActivity.this, "Thingy1", "Load...", false, true);

  site.setWebViewClient(new WebViewClient() {
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
       Log.i(TAG, "Loading...");
       view.loadUrl(url);
       return true;
   }

   public void onPageFinished(WebView view, String url) {
       Log.i(TAG, "Done: " +url);
       if (progressBar.isShowing()) {
           progressBar.dismiss();
       }
   }

   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
       Log.e(TAG, "Error: " + description);
       Toast.makeText(MyActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
       alertDialog.setTitle("Error");
       alertDialog.setMessage(description);
       alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
               return;
           }
       });
       alertDialog.show();
   }
 });

 site.loadUrl("http://www.etcetera.com");

}
like image 255
Martijn Avatar asked Dec 29 '22 06:12

Martijn


1 Answers

Exactly, thanks! I think i found out around the time you wrote the second response ;)

Right now i am using the code below: it works like a charm :) Thank you very much for responding!

site.setWebViewClient(new WebViewClient() {
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
       String myAlternativeURL = "http://newURL";  
       if (!url.equals(myAlternativeURL)) {  
           {
               Intent i = new Intent(Intent.ACTION_VIEW);
               i.setData(Uri.parse("http://newURL"));
               startActivity(i);
               }
           return true;  
       } else {
       Log.i(TAG, "Loading...");
       view.loadUrl(url);
       return true;
   }
   }
like image 117
Martijn Avatar answered Jan 06 '23 12:01

Martijn