Thursday 12 December 2013

How to open url in WebView in android


In this tutorial (post) i am going to explain how we can open an website or url in a web view pragmatically. Usually we open an url by using intent which forces us to open the url in android browser. But if we are making an an application and we want to open an link inside over app. For that this post helps you to achieve that.

First Step:- create the objects of webview and a string which contain the url.

final static String myAddr = "http://itdevelopersdelhi.in";

Second Step:- create the oncreate function and set following properties of the webview.

myWebView = new WebView(this);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setJavaScriptEnabled(true);               
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(myAddr);

Third Step:- Set the webview as the contentView

setContentView(myWebView);

Source Code of the Project :-

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
   
    WebView myWebView;
    //final static String myAddr = "http://android-er.blogspot.com";
    final static String myAddr = "http://itdevelopersdelhi.in/";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        myWebView = new WebView(this);
       
        myWebView.getSettings().setUseWideViewPort(true);
        myWebView.getSettings().setLoadWithOverviewMode(true);
       
        myWebView.getSettings().setJavaScriptEnabled(true);               
        myWebView.setWebViewClient(new WebViewClient());
       
        myWebView.loadUrl(myAddr);
        setContentView(myWebView);
       
    }
   

}

Xml File :-

        No need to make any XML file to run the above code

Manifest file updation :-

       Add the internet permission in the manifest.

Snapshot:-



Click Here To Download the project:-



No comments:

Post a Comment