基本方法如下
1) 建立 Project
2) 修改 main.xml
res/layout/main.xml
<?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"
android:gravity="center_horizontal">
<EditText
android:id="@+id/urlEditor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="1"
android:inputType="textUri"
android:imeOptions="actionGo" />
<Button
android:id="@+id/confirmButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="確定" />
<WebView
android:id="@+id/webview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
3) 修改 HelloWebView.java
src/edu.android.hellowebview/HelloWebView.java
package edu.android.hellowebview;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class HelloWebView extends Activity {
EditText urlEditor;
Button confirmButton;
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.webview1);
urlEditor=(EditText)findViewById(R.id.urlEditor);
confirmButton=(Button)findViewById(R.id.confirmButton);
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OpenUrl();
}
});
urlEditor.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_ENTER){
OpenUrl();
return true;
}
return false;
}
});
}
private void OpenUrl(){
webView.loadUrl("http://"+urlEditor.getText().toString());
}
}
4) 修改 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.android.hellowebview"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="3" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloWebView"
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-permission android:name="android.permission.INTERNET" />
</manifest>
5) 測試結果
沒有留言:
張貼留言