Pages

Tuesday, May 24, 2011

AndroidBrowser, implement a Android Browser using WebView


Webkit, the Android build-in web browser can be embedded in Android Application easily, just include WebView in the layout, main.xml.







Create a New Android Application:
- Project Name: AndroidBrowser
- Application Name: Android Browser
- Package Name: com.exercise.AndroidBrowser
- Create Activity: AndroidBrowser
- Min SDK Version: 3

Modify main.xml to have a WebView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<WebView android:id="@+id/mybrowser" 
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent" 
   />
</LinearLayout>


Modify AndroidBrowser.java
package com.exercise.AndroidBrowser;

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

public class AndroidBrowser extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     String myURL = "http:/z4android.blogspot.com";       
    WebView myBrowser=(WebView)findViewById(R.id.mybrowser);                
    /*By default Javascript is turned off,         
     * it can be enabled by this line.        
     */       
    myBrowser.getSettings().setJavaScriptEnabled(true);                
    myBrowser.loadUrl(myURL);
}
}


You also have make change on AndroidManifest.xml, so your application can access internet:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.exercise.AndroidBrowser"
  android:versionCode="1"
  android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".AndroidBrowser"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
<uses-sdk android:minSdkVersion="3" />

</manifest>

No comments:

Post a Comment

Popular Posts