当前位置: 首页>移动开发>正文

WebView使用

官网提供的例子,很经典。

1. 首先在AndroidManifest.xml中定义访问权限让WebView能访问外部Url,,否则会报Web page not available错误。

<!-- 使html" class="superseo">webview有权限访问外部URL  -->
<uses-permission android:name="android.permission.INTERNET"/>

2. 在Activity中定义一个WebView组件。

<WebView 
android:id="@+id/wv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
/>


3.  定义一个html 存放在 assets/demo.html

<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave() {
alert("1");
document.getElementById("droid").src="xclapplogo.png";
alert("2");
}
</script>
<body>
<!-- Calls into the javascript interface for the activity -->
<a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;" >
<img id="droid" src="img4.png"/><br>
Click me!
</div></a>
</body>
</html>


4.  Activity的代码

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

/**
* Demonstrates how to embed a WebView in your activity. Also demonstrates how
* to have javascript in the WebView call into the activity, and how the activity
* can invoke javascript.
* <p>
* In this example, clicking on the android in the WebView will result in a call into
* the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
* will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
* method.
* <p>
* Obviously all of this could have been accomplished without calling into the activity
* and then back into javascript, but this code is intended to show how to set up the
* code paths for this sort of communication.
*
*/
public class DemoActivity extends Activity {

private static final String LOG_TAG = "WebViewDemo";

private WebView mWebView;

private Handler mHandler = new Handler();

@SuppressLint("JavascriptInterface")
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_wv);
mWebView = (WebView) findViewById(R.id.wv);

WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);

mWebView.setWebChromeClient(new MyWebChromeClient());

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

mWebView.loadUrl("file:///android_asset/demo.html");
}

final class DemoJavaScriptInterface {

DemoJavaScriptInterface() {
}

/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
mWebView.loadUrl("javascript:wave()");
}
});

}
}

/**
* Provides a hook for calling "alert" from javascript. Useful for
* debugging your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
return true;
}
}
}


   onJsAlert  : //如果自定义onJsAlert后,在html页面中使用alert函数时,会调用这个onJsAlert

WebView  mWebView = (WebView) findViewById(R.id.wv);
WebSettings webSettings = mWebView.getSettings();//取得对象

//设置是否支持缩放
webSettings.setBuiltInZoomControls(true);

//是否显示网络图像
webSettings.setBlockNetworkImage(true);

//启用或禁止WebView访问文件数据
webSettings.setAllowFileAccess(true);
//默认字符集
webSettings.setDefaultTextEncodingName("UTF-8");



mWebView.setHorizontalScrollbarOverlay(true);

mWebView.requestFocus();
// 如果不做任何处理,浏览网页,点击系统"Back"键,整个Browser会调用finish()而结束自身,
// 因此如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack(); //goBack()表示返回WebView的上一页面
return true;
}
return false;
}

//显示本地图片文件
private void localImage() {
try{
// 本地文件处理(如果文件名中有空格需要用+来替代)
mWebView.loadUrl("file:///android_asset/xclapplogo.png");
}catch(Exception ex){
//Log.e(tag,ex.printStackTrace());
ex.printStackTrace();
}
}

//显示本地图片文件
private void localLocalFile() {
try{
// 本地文件处理(如果文件名中有空格需要用+来替代)
mWebView.loadUrl("file:///sdcard/screenshot/20131103_134425.png");
}catch(Exception ex){
//Log.e(tag,ex.printStackTrace());
ex.printStackTrace();
}
}

//显示本地图片文件
private void localLocalHtmlFile() {
try{
// 本地文件处理(如果文件名中有空格需要用+来替代)
mWebView.loadUrl("file:///android_asset/index.html");
}catch(Exception ex){
ex.printStackTrace();
}
}

//显示网页字符串
private void localLocalHtmlStr() {

//这个中文还是会乱码
//mWebView.loadData(
// "<html><body><h2> html string 中 </h2> </body></html>",
// "text/html", "UTF-8");

//加上这个("text/html;charset=UTF-8")中文才不会乱码
mWebView.loadData(
"<html><body><h2> html string 中 </h2> </body></html>",
"text/html;charset=UTF-8",null);
}

final String mimeType="text/html";
final String encoding = "utf-8";

private void localLocalHtmlStrUTF8(){

String data = "来看看中文会不会乱码";
try{
//这个也能显示中文
mWebView.loadDataWithBaseURL(null,data,mimeType,encoding,null);
}catch(Exception ex){
//Log.e(tag,ex.printStackTrace());
ex.printStackTrace();
}
}


 


https://www.xamrdz.com/mobile/4c91987455.html

相关文章: