1.xml代码
<ohos.agp.components.webengine.WebView
ohos:id="$+id:webView"
ohos:height="match_content"
ohos:width="match_parent"/>
注意包名一起写,不能直接写 WebView
2.java代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
Navigator navigator = webView.getNavigator();
if (keyCode == keyEvent.KEY_BACK && navigator.canGoBack()) {
navigator.goBack();
return true;
}
return super.onKeyDown(keyCode, keyEvent);
}
private void initWebView() {
webView = findComponentById(ResourceTable.Id_webView);
WebConfig webConfig = webView.getWebConfig();
webConfig.setJavaScriptPermit(true);
webView.setWebAgent(new WebAgent(){
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
return super.isNeedLoadUrl(webView, request);
}
});
webView.load("https://www.baidu.com/");
}
//为了直接这么加载是不会显示任何东西的。加上了以下代码,也可以防止WebView跳转到浏览器
webView.setWebAgent(new WebAgent(){
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
return super.isNeedLoadUrl(webView, request);
}
});
注意增加网络权限和 http权限
{
"name": "ohos.permission.INTERNET",
"reason": "Internet"
},
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
},
|