▼使用軟體時按下前往報名的按鈕,可以直接在軟體中瀏覽報名網頁

▼報名的網頁

一開始必須先在設定檔中加入"android.permission.INTERNET"這個權限,這樣才能允許該軟體使用網路連線。
接著在Layout中加入WebView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="@+id/myWebView"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
</LinearLayout>
在程式碼中呼叫setWebViewClient(WebViewClient client)方法,並把webView加入該方法中,並且利用WebSettings做瀏覽器的設定。
簡化後的程式碼如下:
public class WebViewTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.go_register);
WebView myWebView = (WebView)findViewById(R.id.myWebView);
myWebView.setWebViewClient(new WebViewClient(){});
WebSettings websettings = myWebView.getSettings();
//允許網頁內容可以放大與縮小
websettings.setSupportZoom(true);
websettings.setBuiltInZoomControls(true);
//允許JavaScript
websettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
}
以上語法雖然添加了允許JavaScript的語法,但是若有JavaScript的警告視窗,瀏覽器還是無法支援,需要將語法修改才能夠支援警告視窗。在以下的語法中會用到setWebChromeClient(WebChromeClient client)該方法來添加JavaScripe Diolog。
修改過後的語法:
public class WebViewTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.go_register);
WebView myWebView = (WebView)findViewById(R.id.myWebView);
myWebView.setWebViewClient(new WebViewClient(){});
WebSettings websettings = myWebView.getSettings();
//允許網頁內容可以放大與縮小
websettings.setSupportZoom(true);
websettings.setBuiltInZoomControls(true);
//允許JavaScript
websettings.setJavaScriptEnabled(true);
final Context myApp = this;
/* WebChromeClient must be set BEFORE calling loadUrl! */
myWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result){
new AlertDialog.Builder(myApp)
.setTitle("JavaScript Dialog")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
};
});
myWebView.loadUrl("http://www.google.com");
}
}
▼會跳出Alert Diolog
0 comments:
Post a Comment