1.当只用WebView的时候,最先注意的当然是在配置文件中添加访问因特网的权限;
Java代码
3.如果希望点击链接由自己处理而不是新开Android的系统browser中响应该链接.给WebView添加一个事件监听对象(WebViewClient)并重写其中的一些方法 shouldOverrideUrlLoading对网页中超链接按钮的响应
Java代码
这样就保证了每次打开的页面都是在WebView实例中显示运行的;
4.在显示WebView时,点击手机Back时,会完全退出当前Activity,如果想退到历史浏览页面:重写back监听:
Java代码
5.Android SDK提供了一个schema前缀为"file:///android_asset/".WebView遇到这样的schema,就去当前包中的 assets目录中找内容.如:"file:///android_asset/demo.html"
下面一段代码是对网页中JS的类似Alert()类的函数进行相应的重写响应:
Java代码
在上述代码中,用到的prompt_dialog.xml:
Java代码
还有assets中的Html文件:
Java代码
接着上篇:
6.通过字符串拼凑的html页面显示:
Java代码
7.在同种分辨率的情况下,屏幕密度不一样的情况下,自动适配页面:
Java代码
8.判断加载的页面URL地址是否正确:
Java代码
9.设置WebView的一些缩放功能点:
Java代码
完成java文件:
Java代码
main.xml文件:
Java代码
demo.html:
Java代码
2.如果访问的页面中有Javascript,必须设置支持Javascript:
Java代码
1 | webview.getSettings().setJavaScriptEnabled( true ); |
3.如果希望点击链接由自己处理而不是新开Android的系统browser中响应该链接.给WebView添加一个事件监听对象(WebViewClient)并重写其中的一些方法 shouldOverrideUrlLoading对网页中超链接按钮的响应
Java代码
1 | mWebView.setWebViewClient( new WebViewClient() { |
2 | /** |
3 | * Show in webview not system webview. |
4 | */ |
5 | public boolean shouldOverrideUrlLoading(WebView view, String url) { |
6 | view.loadUrl(url); |
7 | return super .shouldOverrideUrlLoading(view, url); |
8 | } |
9 | } |
这样就保证了每次打开的页面都是在WebView实例中显示运行的;
4.在显示WebView时,点击手机Back时,会完全退出当前Activity,如果想退到历史浏览页面:重写back监听:
Java代码
1 | public boolean onKeyDown( int keyCode, KeyEvent event) { |
2 | WebView mWebView = (WebView) findViewById(R.id.browser); |
3 | if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { |
4 | mWebView.goBack(); |
5 | return true ; |
6 | } |
7 | return super .onKeyDown(keyCode, event); |
8 | } |
5.Android SDK提供了一个schema前缀为"file:///android_asset/".WebView遇到这样的schema,就去当前包中的 assets目录中找内容.如:"file:///android_asset/demo.html"
下面一段代码是对网页中JS的类似Alert()类的函数进行相应的重写响应:
Java代码
001 | webView.setWebChromeClient( new WebChromeClient() { |
002 | public boolean onJsAlert(WebView view, String url, String message, |
003 | final JsResult result) { |
004 | AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs. this ); |
005 | b.setTitle( "Alert" ); |
006 | b.setMessage(message); |
007 | b.setPositiveButton(android.R.string.ok, |
008 | new AlertDialog.OnClickListener() { |
009 | public void onClick(DialogInterface dialog, |
010 | int which) { |
011 | result.confirm(); |
012 | } |
013 | }); |
014 | b.setCancelable( false ); |
015 | b.create(); |
016 | b.show(); |
017 | return true ; |
018 | }; |
019 |
020 | @Override |
021 | public boolean onJsConfirm(WebView view, String url, |
022 | String message, final JsResult result) { |
023 | AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs. this ); |
024 | b.setTitle( "Confirm" ); |
025 | b.setMessage(message); |
026 | b.setPositiveButton(android.R.string.ok, |
027 | new AlertDialog.OnClickListener() { |
028 | public void onClick(DialogInterface dialog, |
029 | int which) { |
030 | result.confirm(); |
031 | } |
032 | }); |
033 | b.setNegativeButton(android.R.string.cancel, |
034 | new DialogInterface.OnClickListener() { |
035 | public void onClick(DialogInterface dialog, |
036 | int which) { |
037 | result.cancel(); |
038 | } |
039 | }); |
040 | b.setCancelable( false ); |
041 | b.create(); |
042 | b.show(); |
043 | return true ; |
044 | }; |
045 |
046 | @Override |
047 | public boolean onJsPrompt(WebView view, String url, String message, |
048 | String defaultValue, final JsPromptResult result) { |
049 | final LayoutInflater factory = LayoutInflater |
050 | .from(BrowserJs. this ); |
051 | final View v = factory.inflate( |
052 | R.layout.prompt_dialog, null ); |
053 | ((TextView) v.findViewById(R.id.prompt_message_text)) |
054 | .setText(message); |
055 | ((EditText) v.findViewById(R.id.prompt_input_field)) |
056 | .setText(defaultValue); |
057 |
058 | AlertDialog.Builder b = new AlertDialog.Builder(BrowserJs. this ); |
059 | b.setTitle( "Prompt" ); |
060 | b.setView(v); |
061 | b.setPositiveButton(android.R.string.ok, |
062 | new AlertDialog.OnClickListener() { |
063 | public void onClick(DialogInterface dialog, |
064 | int which) { |
065 | String value = ((EditText) v |
066 | .findViewById(R.id.prompt_input_field)) |
067 | .getText().toString(); |
068 | result.confirm(value); |
069 | } |
070 | }); |
071 | b.setNegativeButton(android.R.string.cancel, |
072 | new DialogInterface.OnClickListener() { |
073 | public void onClick(DialogInterface dialog, |
074 | int which) { |
075 | result.cancel(); |
076 | } |
077 | }); |
078 | b.setOnCancelListener( new DialogInterface.OnCancelListener() { |
079 | public void onCancel(DialogInterface dialog) { |
080 | result.cancel(); |
081 | } |
082 | }); |
083 | b.show(); |
084 | return true ; |
085 | }; |
086 |
087 | public void onProgressChanged(WebView view, int newProgress) { |
088 | BrowserJs. this .getWindow().setFeatureInt( |
089 | Window.FEATURE_PROGRESS, newProgress * 100 ); |
090 | super .onProgressChanged(view, newProgress); |
091 | } |
092 |
093 | public void onReceivedTitle(WebView view, String title) { |
094 | BrowserJs. this .setTitle(title); |
095 | super .onReceivedTitle(view, title); |
096 | } |
097 | }); |
098 |
099 | go.setOnClickListener( new OnClickListener() { |
100 | public void onClick(View view) { |
101 | String url = text.getText().toString(); |
102 | webView.loadUrl(url); |
103 | } |
104 | }); |
105 | webView.loadUrl( "file:///android_asset/index.html" ); |
在上述代码中,用到的prompt_dialog.xml:
Java代码
01 | <?xml version= "1.0" encoding= "utf-8" ?> |
02 | <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" |
03 | android:gravity= "center_horizontal" android:orientation= "vertical" |
04 | android:layout_width= "fill_parent" android:layout_height= "wrap_content" > |
05 | <TextView android:id= "@+id/prompt_message_text" |
06 | android:layout_width= "fill_parent" android:layout_height= "wrap_content" /> |
07 | <EditText android:id= "@+id/prompt_input_field" |
08 | android:layout_width= "fill_parent" android:layout_height= "wrap_content" |
09 | android:selectAllOnFocus= "true" android:scrollHorizontally= "true" |
10 | android:minWidth= "250dp" /> |
11 | </LinearLayout> |
还有assets中的Html文件:
Java代码
01 | <html> |
02 | <script type= "text/javascript" > |
03 | function onAlert(){ |
04 | alert( "This is a alert sample from html" ); |
05 | } |
06 | function onConfirm(){ |
07 | var b=confirm( "are you sure to login?" ); |
08 | alert( "your choice is " +b); |
09 | } |
10 | function onPrompt(){ |
11 | var b=prompt( "please input your password" , "aaa" ); |
12 | alert( "your input is " +b); |
13 | } |
14 | </script> |
15 | <pre> |
16 | <input type= "button" value= "alert" /> |
17 | <input type= "button" value= "confirm" /> |
18 | <input type= "button" value= "prompt" /> |
19 |
20 | <a href= "http://www.google.com" />Google</a> |
21 | </pre> |
22 | </html> |
接着上篇:
6.通过字符串拼凑的html页面显示:
Java代码
01 | public void simpleJsClick() { |
02 | WebView webView = (WebView) findViewById(R.id.webview); |
03 | String html = "<html>" |
04 | + "<body>" |
05 | + "图书封面<br>" |
06 | + "<table width='200' border='1' >" |
07 | + "<tr>" |
08 | + "<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>" |
09 | + "<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>" |
10 | + "</tr>" |
11 | + "<tr>" |
12 | + "<td><img style='margin:10px' src='http://images.china-pub.com/ebook25001-30000/27518/zcover.jpg' width='100'/></td>" |
13 | + "<td><img style='margin:10px' src='http://images.china-pub.com/ebook30001-35000/34838/zcover.jpg' width='100'/></td>" |
14 | + "</tr>" + "</table>" + "</body>" + "</html>" ; |
15 |
16 | webView.loadDataWithBaseURL( null , html, "text/html" , "utf-8" , null ); |
17 | webView.getSettings().setJavaScriptEnabled( true ); |
18 | webView.setWebChromeClient( new WebChromeClient()); |
19 | } |
7.在同种分辨率的情况下,屏幕密度不一样的情况下,自动适配页面:
Java代码
1 | DisplayMetrics dm = getResources().getDisplayMetrics(); |
2 | int scale = dm.densityDpi; |
3 | if (scale == 240 ) { // |
4 | webView.getSettings().setDefaultZoom(ZoomDensity.FAR); |
5 | } else if (scale == 160 ) { |
6 | webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM); |
7 | } else { |
8 | webView.getSettings().setDefaultZoom(ZoomDensity.CLOSE); |
9 | } |
8.判断加载的页面URL地址是否正确:
Java代码
1 | if (URLUtil.isNetworkUrl(url)== true ) |
9.设置WebView的一些缩放功能点:
Java代码
1 | webView.getSettings().setJavaScriptEnabled( true ); |
2 | webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); |
3 | webView.setHorizontalScrollBarEnabled( false ); |
4 | webView.getSettings().setSupportZoom( true ); |
5 | webView.getSettings().setBuiltInZoomControls( true ); |
6 | webView.setInitialScale( 70 ); |
7 | webView.setHorizontalScrollbarOverlay( true ); |
完成java文件:
Java代码
01 | public class MethodMutual extends Activity { |
02 |
03 | private WebView mWebView; |
04 | private Handler mHandler = new Handler(); |
05 | private static final String LOG_TAG = "WebViewDemo" ; |
06 |
07 | /** Called when the activity is first created. */ |
08 | @Override |
09 | public void onCreate(Bundle savedInstanceState) { |
10 | super .onCreate(savedInstanceState); |
11 | setContentView(R.layout.main); |
12 | loadAssetHtml(); |
13 | } |
14 |
15 | public void loadAssetHtml() { |
16 | mWebView = (WebView) findViewById(R.id.webview); |
17 | WebSettings webSettings = mWebView.getSettings(); |
18 | webSettings.setSavePassword( false ); |
19 | webSettings.setSaveFormData( false ); |
20 | webSettings.setJavaScriptEnabled( true ); |
21 | webSettings.setSupportZoom( false ); |
22 | mWebView.setWebChromeClient( new MyWebChromeClient()); |
23 | // 将一个java对象绑定到一个javascript对象中,javascript对象名就是interfaceName,作用域是Global. |
24 | mWebView.addJavascriptInterface( new DemoJavaScriptInterface(), "demo" ); |
25 | mWebView.loadUrl( "file:///android_asset/demo.html" ); |
26 | // 通过应用中按钮点击触发JS函数响应 |
27 | Button mCallJS = (Button) findViewById(R.id.mCallJS); |
28 | mCallJS.setOnClickListener( new OnClickListener() { |
29 | @Override |
30 | public void onClick(View v) { |
31 | mWebView.loadUrl( "javascript:wave()" ); |
32 | } |
33 | }); |
34 | } |
35 |
36 | private int i = 0 ; |
37 |
38 | final class DemoJavaScriptInterface { |
39 | DemoJavaScriptInterface() { |
40 | } |
41 | /** |
42 | * This is not called on the UI thread. Post a runnable to invoke |
43 | * loadUrl on the UI thread. |
44 | */ |
45 | public void callAndroid() { |
46 | mHandler.post( new Runnable() { |
47 | public void run() { |
48 | if (i % 2 == 0 ) { |
49 | mWebView.loadUrl( "javascript:wave()" ); |
50 | } else { |
51 | mWebView.loadUrl( "javascript:waveBack()" ); |
52 | } |
53 | i++; |
54 | } |
55 | }); |
56 | } |
57 | } |
58 |
59 | /** |
60 | * Provides a hook for calling "alert" from javascript. Useful for debugging |
61 | * your javascript. |
62 | */ |
63 | final class MyWebChromeClient extends WebChromeClient { |
64 | @Override |
65 | public boolean onJsAlert(WebView view, String url, String message, |
66 | JsResult result) { |
67 | Log.d(LOG_TAG, message); |
68 | result.confirm(); |
69 | return true ; |
70 | } |
71 | } |
72 | } |
main.xml文件:
Java代码
1 | <?xml version= "1.0" encoding= "utf-8" ?> |
2 | <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" |
3 | android:orientation= "vertical" android:layout_width= "fill_parent" |
4 | android:layout_height= "fill_parent" > |
5 | <Button android:layout_width= "wrap_content" android:text= "CallJs" |
6 | android:layout_height= "wrap_content" android:id= "@+id/mCallJS" /> |
7 | <WebView android:id= "@+id/webview" android:layout_width= "fill_parent" |
8 | android:layout_height= "fill_parent" /> |
9 | </LinearLayout> |
demo.html:
Java代码
01 | <html> |
02 | <script language= "javascript" > |
03 | /* This function is invoked by the activity */ |
04 | function wave() { |
05 | alert("1"); |
06 | document.getElementById("droid").src="android_waving.png"; |
07 | alert("2"); |
08 | } |
09 | /* This function is invoked by the activity */ |
10 | function waveBack() { |
11 | alert( "1" ); |
12 | document.getElementById( "droid" ).src= "android_normal.png" ; |
13 | alert( "2" ); |
14 | } |
15 | </script> |
16 | <body> |
17 | <!-- Calls into the javascript interface for the activity --> |
18 | <a><div style="width:80px; |
19 | margin:0px auto; |
20 | padding:10px; |
21 | text-align:center; |
22 | border:2px solid # 202020 ;" > |
23 | <img id= "droid" src= "android_normal.png" /><br> |
24 | Click me! |
25 | </div></a> |
26 | </body> |
27 | </html> |