Wednesday, February 20, 2013

How to display webpage from website on Android using WebView class

Android WebView class allows viewing a specified website URL from within an Android app without opening a web browser.

1. Create a new JAVA class called WebViewer.java and paste the following code

package com.samples.webexample;

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


public class WebViewer extends DashboardActivity
{


 private WebView webView;
protected void onCreate(Bundle savedInstanceState)
{
   
  super.onCreate(savedInstanceState);       
  setContentView(R.layout.main);        


  // Create reference to UI elements       
  webView  = (WebView) findViewById(R.id.webview_compontent);       
             
  // workaround so that the default browser doesn't take over       
  webView.setWebViewClient(new MyWebViewClient());          

     
  // Setup click listener  
  openURL(); 
  }       


 /** Opens the URL in a browser */   
 private void openURL() {    

  webView.loadUrl("
http://www.mywebsite.com/about.html");
  webView.requestFocus();   
  }       


 private class MyWebViewClient extends WebViewClient {       
  @Override       
  public boolean shouldOverrideUrlLoading(WebView view, String url) {           
   view.loadUrl(url);           
   return true;       
   }   
  }
   
}


2. Create a new layout file named main.xml and paste the following code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"  
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent">


                  <WebView   
                      android:id="@+id/webview_compontent"    
                      android:layout_width="fill_parent"     
                      android:layout_height="fill_parent"     
                      android:layout_weight="1.0"    />
</LinearLayout>


3. Add the following line to your Android manifest file if you are calling this activity from another activity

      <activity android:name=".WebViewer">
      </activity>

No comments:

Post a Comment

Post a Comment