Monday, April 05, 2010

Android WebView

WebView allows you to create your own window for viewing web pages (or even develop a complete browser). In this tutorial, you'll create a simple Activity that can view and navigate web pages.




1.Create a new project named HelloWebView.
2.Open the res/layout/main.xml file and insert the following:


android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

3.Now open the HelloWebView.java file. At the top of the class, declare a WebView object:

WebView mWebView;

Then use the following code for the onCreate() method:

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("http://www.thomasyounsi.com");
}
This initializes the member WebView with the one from the Activity layout;
requests a WebSettings object with getSettings();
and enables JavaScript for the WebView with setJavaScriptEnabled(boolean).
Finally, an initial web page is loaded with loadUrl(String).

4.Because this application needs access to the Internet, you need to add the appropriate permissions to the Android manifest file.
Open the AndroidManifest.xml file and add the following as a child of the element:


What is very powerful with WebView is that you can use a two way communication between the content which is display in the web view and the Java application. This can be accomplished by using JavaScript running inside the WebView calling out Java code to get the updated fragment for the HTML div bloc that require to be use to update the content running inside the view. This means you can use HTML div to layout your content and expand/collapse a div based on user action. The content can come from a remote database, a web service or as a JSON Object.




http://www.youtube.com/watch?v=Ex7YsQ_YH2U

No comments: