WebView组件
在实际的App开发中,我们往往还会直接跳转到网页。比如微信人家给你发了一个链接,默认也是在App之内打开的。
当然,很多公司的App就只使用一个WebView作为整体框架,比如我们常用的读书App:掌阅等。这样开发的好处是,只要使用少量的代码即可完成交互。
所以,今天我们将来介绍鸿蒙App的WebView组件的使用方式。
基本用法
首先,与前面讲解的其他组件一样,这里通过XML布局文件进行操作。示例代码如下:
<ohos.agp.components.webengine.WebView
ohos:id="$+id:ability_main_webview"
ohos:height="match_parent"
ohos:width="match_parent"/>
需要注意的是,博主这里输入的是ohos.agp.components.webengine.WebView,你直接输入WebView也是有提示的。
不过,WebView与ohos.agp.components.webengine.WebView并不等价,这可能是鸿蒙的一个漏洞,直接输入WebView并不能使用这个组件。
接下来,就需要加载我们的网页进行显示,代码如下所示:
public class MainAbilitySlice extends AbilitySlice {
private WebView webView;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
this.webView=(WebView)findComponentById(ResourceTable.Id_ability_main_webview);
this.webView.load("https://www.baidu.com");
}
}
很简单,我们使用load()函数进行网页的加载。不过,在主界面,直接这么加载是不会显示任何东西的。
防止WebView跳转到浏览器
这是因为,鸿蒙默认的WebView组件是直接跳转到浏览器的,而你在主页这么做,那连显示都不必,何必安装App呢?
所以,我们需要禁止WebView跳转到浏览器,它才可能在主页显示这个组件。而它的setWebAgent()方法就是防止跳转浏览器的。示例如下:
public class MainAbilitySlice extends AbilitySlice {
private WebView webView;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
this.webView=(WebView)findComponentById(ResourceTable.Id_ability_main_webview);
this.webView.setWebAgent(new WebAgent(){
@Override
public boolean isNeedLoadUrl(WebView webView, ResourceRequest request)