1、通过XML初始化:
或者直接New:
WebView webview = newWebView( this);
2、加载URL:
WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.loadUrl("http://www.example.com");或者可以直接加载Html:String summary = "
You scored 192 points. ";myWebView.loadData(summary, "text/html", null);如果在加载URL的时候想添加Header信息,可以复写loadUrl()方法,如:
@ Override publicvoidloadUrl(String url){ Map map= newHashMap();
map.put( "ajax", "true");
map.put( "appversion", SharedPreferencesUtil.getAppVersion(getContext())); map.put( "clientid", SharedPreferencesUtil.getClientId(getContext())); loadUrl(url, map); }
WebSettings
WebSettings 中可以对WebView进行一系列配置,如:
WebSettings settings = getSettings(); //默认是false 设置true允许和js交互settings.setJavaEnabled( true); // WebSettings.LOAD_DEFAULT 如果本地缓存可用且没有过期则使用本地缓存,否加载网络数据 默认值// WebSettings.LOAD_CACHE_ELSE_NETWORK 优先加载本地缓存数据,无论缓存是否过期// WebSettings.LOAD_NO_CACHE 只加载网络数据,不加载本地缓存// WebSettings.LOAD_CACHE_ONLY 只加载缓存数据,不加载网络数据//Tips:有网络可以使用LOAD_DEFAULT 没有网时用LOAD_CACHE_ELSE_NETWORKsettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //开启 DOM storage API 功能 较大存储空间,使用简单settings.setDomStorageEnabled( true); //设置数据库缓存路径 存储管理复杂数据 方便对数据进行增加、删除、修改、查询 不推荐使用settings.setDatabaseEnabled( true); finalString dbPath = context.getApplicationContext().getDir( "db", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(dbPath); //开启 Application Caches 功能 方便构建离线APP 不推荐