You are on page 1of 4

WebView

Project : WebViewDemo

สําหรับโปรเจ็กนี้ จะแนะนําให้รู้จักกับ WebView สําหรับการเปิด Web

<?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" >

<WebView
android:id = "@+id/webView"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:layout_margin = "5dip" >
</WebView>

</LinearLayout>

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

Code XML ในการจัด Layout ของ LinearLayout


orientation : อะไรก็ตามที่ใส่เข้าไปใน linear จะเรียงต่อกันตามแนวดิ่ง
width : กว้าง เท่ากับขนาดของ parent ในที่นี้ คือ จอภาพ
height : สูง เท่ากับขนาดของ parent ในที่นี้ คือ จอภาพ
<WebView
android:id = "@+id/webView"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:layout_margin = "5dip" >
</WebView>

Code XML ในการจัด Layout ของ WebView


id : มีชื่อตัวแปรว่า webView
width : กว้าง เท่ากับขนาดของ parent ในที่นี้ LinearLayout
height : สูง เท่ากับขนาดของ parent ในที่นี้ LinearLayout

จากนั้นเราก็ไปเพิ่ม Code ในส่วนของ AndroidManifest.xml


ว่า : <uses-permission android:name = "android.permission.INTERNET" />
เพื่อให้มีการเชื่อต่อ Internet จะได้ว่า

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="bom.WebViewDemo"
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=".WebViewDemo"
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>
</manifest>
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewDemo extends Activity {

WebView webView;

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

webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");

}
}

WebView webView;

Code Java ในการประกาศตัวแปร WebView

webView = (WebView)findViewById(R.id.webView);

Code Java ในการการเชื่อม ตัวแปร WebView กับ Layout ( XML )


จากนั้นเราก็มากําหนดให้ WebView ของเรา สามารถอ่าน JavaScript ได้
ด้วยฟังก์ชัน getSetting().setJavaScriptEnabled() จะได้ว่า

webView.getSettings().setJavaScriptEnabled(true);

จากนั้นเราก็ เปิด Web ด้วยฟังก์ชัน loadUrl() จะได้ว่า

webView.loadUrl("http://www.google.com");

drbomkung@gmail.com

You might also like