WebView使用總結(應用函數與JS函數互相調用)

1.當只用WebView的時候,最早注意的固然是在配置文件中添加訪問因特網的權限;

2.若是訪問的頁面中有Javascript,必須設置支持Javascript:

Java代碼
?
代碼片斷,雙擊複製
01
webview.getSettings().setJavaScriptEnabled(true);



3.若是但願點擊連接由本身處理而不是新開Android的系統browser中響應該連接.給WebView添加一個事件監聽對象(WebViewClient)並重寫其中的一些方法 shouldOverrideUrlLoading對網頁中超連接按鈕的響應
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
mWebView.setWebViewClient(newWebViewClient() {
/**
* Show in webview not system webview.
*/
publicbooleanshouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
returnsuper.shouldOverrideUrlLoading(view, url);
}
}


這樣就保證了每次打開的頁面都是在WebView實例中顯示運行的;

4.在顯示WebView時,點擊手機Back時,會徹底退出當前Activity,若是想退到歷史瀏覽頁面:重寫back監聽:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
publicbooleanonKeyDown(intkeyCode, KeyEvent event) {
WebView mWebView = (WebView) findViewById(R.id.browser);
if((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
returntrue;
}
returnsuper.onKeyDown(keyCode, event);
}


5.Android SDK提供了一個schema前綴爲"file:///android_asset/".WebView遇到這樣的schema,就去當前包中的 assets目錄中找內容.如:"file:///android_asset/demo.html"
下面一段代碼是對網頁中JS的相似Alert()類的函數進行相應的重寫響應:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
webView.setWebChromeClient(newWebChromeClient() {
publicbooleanonJsAlert(WebView view, String url, String message,
finalJsResult result) {
AlertDialog.Builder b =newAlertDialog.Builder(BrowserJs.this);
b.setTitle("Alert");
b.setMessage(message);
b.setPositiveButton(android.R.string.ok,
newAlertDialog.OnClickListener() {
publicvoidonClick(DialogInterface dialog,
intwhich) {
result.confirm();
}
});
b.setCancelable(false);
b.create();
b.show();
returntrue;
};
@Override
publicbooleanonJsConfirm(WebView view, String url,
String message,finalJsResult result) {
AlertDialog.Builder b =newAlertDialog.Builder(BrowserJs.this);
b.setTitle("Confirm");
b.setMessage(message);
b.setPositiveButton(android.R.string.ok,
newAlertDialog.OnClickListener() {
publicvoidonClick(DialogInterface dialog,
intwhich) {
result.confirm();
}
});
b.setNegativeButton(android.R.string.cancel,
newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog,
intwhich) {
result.cancel();
}
});
b.setCancelable(false);
b.create();
b.show();
returntrue;
};
@Override
publicbooleanonJsPrompt(WebView view, String url, String message,
String defaultValue,finalJsPromptResult result) {
finalLayoutInflater factory = LayoutInflater
.from(BrowserJs.this);
finalView v = factory.inflate(
R.layout.prompt_dialog,null);
((TextView) v.findViewById(R.id.prompt_message_text))
.setText(message);
((EditText) v.findViewById(R.id.prompt_input_field))
.setText(defaultValue);
AlertDialog.Builder b =newAlertDialog.Builder(BrowserJs.this);
b.setTitle("Prompt");
b.setView(v);
b.setPositiveButton(android.R.string.ok,
newAlertDialog.OnClickListener() {
publicvoidonClick(DialogInterface dialog,
intwhich) {
String value = ((EditText) v
.findViewById(R.id.prompt_input_field))
.getText().toString();
result.confirm(value);
}
});
b.setNegativeButton(android.R.string.cancel,
newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog,
intwhich) {
result.cancel();
}
});
b.setOnCancelListener(newDialogInterface.OnCancelListener() {
publicvoidonCancel(DialogInterface dialog) {
result.cancel();
}
});
b.show();
returntrue;
};
publicvoidonProgressChanged(WebView view,intnewProgress) {
BrowserJs.this.getWindow().setFeatureInt(
Window.FEATURE_PROGRESS, newProgress *100);
super.onProgressChanged(view, newProgress);
}
publicvoidonReceivedTitle(WebView view, String title) {
BrowserJs.this.setTitle(title);
super.onReceivedTitle(view, title);
}
});
go.setOnClickListener(newOnClickListener() {
publicvoidonClick(View view) {
String url = text.getText().toString();
webView.loadUrl(url);
}
});
webView.loadUrl("file:///android_asset/index.html");


在上述代碼中,用到的prompt_dialog.xml:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"android:orientation="vertical"
android:layout_width="fill_parent"android:layout_height="wrap_content">
<TextView android:id="@+id/prompt_message_text"
android:layout_width="fill_parent"android:layout_height="wrap_content"/>
<EditText android:id="@+id/prompt_input_field"
android:layout_width="fill_parent"android:layout_height="wrap_content"
android:selectAllOnFocus="true"android:scrollHorizontally="true"
android:minWidth="250dp"/>
</LinearLayout>


還有assets中的Html文件:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<script type="text/javascript">
function onAlert(){
alert("This is a alert sample from html");
}
function onConfirm(){
var b=confirm("are you sure to login?");
alert("your choice is "+b);
}
function onPrompt(){
var b=prompt("please input your password","aaa");
alert("your input is "+b);
}
</script>
<pre>
<input type="button"value="alert"/>
<input type="button"value="confirm"/>
<input type="button"value="prompt"/>
<a href="http://www.google.com"/>Google</a>
</pre>
</html>


接着上篇:
6.經過字符串拼湊的html頁面顯示:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
publicvoidsimpleJsClick() {
WebView webView = (WebView) findViewById(R.id.webview);
String html ="<html>"
+"<body>"
+"圖書封面<br>"
+"<table width='200' border='1' >"
+"<tr>"
+"<td><a onclick='alert(\"Java Web開發速學寶典\")' ><img style='margin:10px' src='http://images.china-pub.com/ebook45001-50000/48015/cover.jpg' width='100'/></a></td>"
+"<td><a onclick='alert(\"大象--Thinking in UML\")' ><img style='margin:10px' src='http://images.china-pub.com/ebook125001-130000/129881/zcover.jpg' width='100'/></td>"
+"</tr>"
+"<tr>"
+"<td><img style='margin:10px' src='http://images.china-pub.com/ebook25001-30000/27518/zcover.jpg' width='100'/></td>"
+"<td><img style='margin:10px' src='http://images.china-pub.com/ebook30001-35000/34838/zcover.jpg' width='100'/></td>"
+"</tr>"+"</table>"+"</body>"+"</html>";
webView.loadDataWithBaseURL(null, html,"text/html","utf-8",null);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(newWebChromeClient());
}


7.在同種分辨率的狀況下,屏幕密度不同的狀況下,自動適配頁面:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
DisplayMetrics dm = getResources().getDisplayMetrics();
intscale = dm.densityDpi;
if(scale ==240) {//
webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
}elseif(scale ==160) {
webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);
}else{
webView.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
}


8.判斷加載的頁面URL地址是否正確:
Java代碼


?
代碼片斷,雙擊複製
01
if(URLUtil.isNetworkUrl(url)==true)


9.設置WebView的一些縮放功能點:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setHorizontalScrollBarEnabled(false);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setInitialScale(70);
webView.setHorizontalScrollbarOverlay(true);


完成java文件:
Java代碼


?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
publicclassMethodMutualextendsActivity {
privateWebView mWebView;
privateHandler mHandler =newHandler();
privatestaticfinalString LOG_TAG ="WebViewDemo";
/** Called when the activity is first created. */
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadAssetHtml();
}
publicvoidloadAssetHtml() {
mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setWebChromeClient(newMyWebChromeClient());
// 將一個java對象綁定到一個javascript對象中,javascript對象名就是interfaceName,做用域是Global.
mWebView.addJavascriptInterface(newDemoJavaScriptInterface(),"demo");
mWebView.loadUrl("file:///android_asset/demo.html");
// 經過應用中按鈕點擊觸發JS函數響應
Button mCallJS = (Button) findViewById(R.id.mCallJS);
mCallJS.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
mWebView.loadUrl("javascript:wave()");
}
});
}
privateinti =0;
finalclassDemoJavaScriptInterface {
DemoJavaScriptInterface() {
}
/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
publicvoidcallAndroid() {
mHandler.post(newRunnable() {
publicvoidrun() {
if(i %2==0) {
mWebView.loadUrl("javascript:wave()");
}else{
mWebView.loadUrl("javascript:waveBack()");
}
i++;
}
});
}
}
/**
* Provides a hook for calling "alert" from javascript. Useful for debugging
* your javascript.
*/
finalclassMyWebChromeClientextendsWebChromeClient {
@Override
publicbooleanonJsAlert(WebView view, String url, String message,
JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
returntrue;
}
}
}


main.xml文件:
Java代碼

?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
<?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">
<Button android:layout_width="wrap_content"android:text="CallJs"
android:layout_height="wrap_content"android:id="@+id/mCallJS"/>
<WebView android:id="@+id/webview"android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>


demo.html:
Java代碼

?
代碼片斷,雙擊複製
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave() {
alert("1");
document.getElementById("droid").src="android_waving.png";
alert("2");
}
/* This function is invoked by the activity */
function waveBack() {
alert("1");
document.getElementById("droid").src="android_normal.png";
alert("2");
}
</script>
<body>
<!-- Calls into the javascriptinterfaceforthe activity -->
<a><div style="width:80px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;" >
<img id="droid"src="android_normal.png"/><br>
Click me!
</div></a>
</body>
</html>
相關文章
相關標籤/搜索