Tuesday, November 8, 2011

How to use a WebView and navigate inside it

As you may know Android provides the WebView control that allows you to show a web page inside your activity very nice. Just drag & drop from the "designer" into your Activity and that's it.
Ok, but after placing your WebView you notice that when you click in one link it opens the default web browser and bye bye your app.
Well to keep the navigation in your app. Check this snipped.

public class WebActivity extends Activity {
 public final static String URL = "URL";
 private WebView mWebClient;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.web_navigation);

  mWebClient = (WebView)this.findViewById(R.id.webViewSpace);

  Bundle bundle = this.getIntent().getExtras();
  String url = bundle.getString(URL);
  
//Next line to make continue navigating inside our WebView
  mWebClient.setWebViewClient(new WebViewClient(){

   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
   }
  });  

  mWebClient.loadUrl(url);
 }
}

To avoid loading the page in other activity just neeeeds to extends a WebViewClient, in here I just created an anonymous class cause I'm lazzy but you may extend in a formal class and do stuff like filter only your site trafic, and any other let the browser manage.


No comments:

Post a Comment