1. 打开官网,找到WebView的文档(模拟器不支持)

    鸿蒙webview的开发指南(原始链接,方便大家识别并点击):https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158



2. 创建一个Page Ability,把基本布局弄好

下面是代码

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<DirectionalLayout
ohos:height="30vp"
ohos:width="match_parent"
ohos:orientation="horizontal">
<TextField
ohos:id="$+id:text_webView_Url"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="$graphic:background_ability_simple_web_view"
ohos:focus_border_enable="true"
ohos:hint="请输入网址"
ohos:max_text_lines="1"
ohos:multiple_lines="false"
ohos:scrollable="true"
ohos:text="www.harmonyos.com"
ohos:text_size="50"
ohos:weight="1"
/>
<Button
ohos:id="$+id:button_webview_surf"
ohos:height="match_content"
ohos:width="60vp"
ohos:background_element="$graphic:button_element"
ohos:text="跳转"
ohos:text_size="50"/>
</DirectionalLayout>
<ProgressBar
ohos:id="$+id:other_webView_progressBar"
ohos:height="10vp"
ohos:width="match_parent"
ohos:visibility="hide">
</ProgressBar>
<ohos.agp.components.webengine.WebView
ohos:id="$+id:webview_webview_webview"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:weight="1">
</ohos.agp.components.webengine.WebView>
<DirectionalLayout
ohos:height="30vp"
ohos:width="match_parent"
ohos:orientation="horizontal">
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:weight="1">
<Button
ohos:id="$+id:button_webview_back"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="$graphic:button_element"
ohos:layout_alignment="horizontal_center"
ohos:text="向后"
ohos:text_size="50"
>
</Button>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:weight="1">
<Button
ohos:id="$+id:button_webview_refresh"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="$graphic:button_element"
ohos:layout_alignment="horizontal_center"
ohos:text="刷新"
ohos:text_size="50">
</Button>
</DirectionalLayout>
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:weight="1">
<Button
ohos:id="$+id:button_webview_forward"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="$graphic:button_element"
ohos:layout_alignment="horizontal_center"
ohos:text="向前"
ohos:text_size="50">
</Button>
</DirectionalLayout>
</DirectionalLayout>
</DirectionalLayout>
  1. 把基本的按钮事件弄好

    序号 按钮 功能
    1 跳转 把文本框中的网址打开
    2 后退 在webview中点了新链接后,想回去看一看
    3 刷新 以前的人在网络不好,美女图片出不来的时候用,现在一般是发了一篇帖子后,作者会没事点一下,看看有没有人点赞
    4 前进 跟后退是关联用的,就是点了新链接,回去看了看后,还是觉得新链接更好看,就又要前进.

    代码

        Component.ClickedListener clickedListener = new Component.ClickedListener() {
    @Override
    public void onClick(Component component) {
    int componentId = component.getId();
    switch (componentId) {
    case ResourceTable.Id_button_webview_surf: {
    urlAddress = textWebViewUrl.getText();
    if (urlAddress.isEmpty()) {
    return;
    }
    if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) {
    urlAddress = FinalValue.URL_HTTPS + urlAddress;
    }
    webView.load(urlAddress); }
    break;
    case ResourceTable.Id_button_webview_back: {
    if (webView.getNavigator().canGoBack()) {
    webView.getNavigator().goBack();
    }
    }
    break;
    case ResourceTable.Id_button_webview_refresh: {
    webView.reload();
    }
    break;
    case ResourceTable.Id_button_webview_forward: {
    if (webView.getNavigator().canGoForward()) {
    webView.getNavigator().goForward();
    }
    }
    break;
    default: {
    System.out.println("没有选择任何的页面");
    }
    break;
    }
    }
    };
    - config.json ``` json
    {
    "app": {
    "bundleName": "com.javaaier.family.huawei",
    "vendor": "javaaier",
    "version": {
    "code": 1,
    "name": "1.0"
    },
    "apiVersion": {
    "compatible": 5,
    "target": 5,
    "releaseType": "Beta1"
    }
    },
    "deviceConfig": { },
    "module": {
    "package": "com.javaaier.family.huawei",
    "name": ".MyApplication",
    "deviceType": [
    "phone"
    ],
    "distro": {
    "deliveryWithInstall": true,
    "moduleName": "entry",
    "moduleType": "entry"
    },
    "abilities": [
    {
    "skills": [
    {
    "entities": [
    "entity.system.home"
    ],
    "actions": [
    "action.system.home"
    ]
    }
    ],
    "orientation": "unspecified",
    "name": "com.javaaier.family.huawei.MainAbility",
    "icon": "$media:icon",
    "description": "$string:mainability_description",
    "label": "$string:app_name",
    "type": "page",
    "launchType": "standard"
    },
    {
    "orientation": "unspecified",
    "name": "com.javaaier.family.huawei.SimpleWebViewAbility",
    "icon": "$media:icon",
    "description": "$string:simplewebviewability_description",
    "label": "$string:app_name",
    "type": "page",
    "launchType": "standard"
    }
    ],
    "reqPermissions": [
    {
    "name": "ohos.permission.INTERNET"
    }
    ]
    }
    }
  • 把WebView照文档上面的要求弄好

    没啥好说的,就是规定.我加在了调用load方法打开网址那行代码后面,我还弄了一个跟进度条关联的功能

      //允许javascript交互
    
                        WebConfig webConfig = webView.getWebConfig();
    webConfig.setDataAbilityPermit(true);
    webConfig.setJavaScriptPermit(true);
    webConfig.setLoadsImagesPermit(true);
    webConfig.setMediaAutoReplay(true);
    webConfig.setLocationPermit(true);
    webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE); webView.setWebAgent(new WebAgent() {
    @Override
    public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
    super.onLoadingPage(webView, url, favicon);
    // 这儿我加了一个更新网址文本框中新页面url的功能
    if (url != urlAddress) {
    textWebViewUrl.setText(url);
    } } @Override
    public void onPageLoaded(WebView webView, String url) {
    super.onPageLoaded(webView, url);
    // 页面加载结束后自定义处理
    } @Override
    public void onLoadingContent(WebView webView, String url) {
    super.onLoadingContent(webView, url);
    // 加载资源时自定义处理
    } @Override
    public void onError(WebView webView, ResourceRequest request, ResourceError error) {
    super.onError(webView, request, error);
    // 发生错误时自定义处理
    }
    });
    webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) {
    @Override
    public void onTitleUpdated(WebView webView, String title) {
    super.onTitleUpdated(webView, title);
    // 标题变更时自定义处理
    } @Override
    public void onProgressUpdated(WebView webView, int newProgress) {
    super.onProgressUpdated(webView, newProgress);
    if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) {
    otherWebViewProgressBar.setVisibility(Component.VISIBLE);
    otherWebViewProgressBar.setProgressValue(newProgress);
    } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) {
    otherWebViewProgressBar.setVisibility(Component.HIDE);
    }
    // 加载进度变更时自定义处理
    }
    });
  • 完事?or完了还有事?

    从上面拷代码的话,估计完事了.但是,我是用的回忆,但是代码却没有回退,所以我还是有必要在这儿把步骤中的问题说一说,方便不拷代码的同学也能跑出一个界面.主要体现如下:

    1. 权限配置,不多说

       "reqPermissions": [
      {
      "name": "ohos.permission.INTERNET"
      }
      ]
  • xml中的WebView要带包名

      <ohos.agp.components.webengine.WebView
    ohos:id="$+id:webview_webview_webview"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:weight="1">
    </ohos.agp.components.webengine.WebView>
    1. 不按上面包名写的话:

      • 真机运行后没有WebView的界面.哪怕weight=1,也不行
      • 点击跳转按钮后,PageAbility会闪退,回到首屏(调用它的页面)

    完事效果:https://www.bilibili.com/video/BV1tK4y1o7Hz/

  • 完整代码

    • 布局

      序号为2的步骤中贴全了

    • 按钮背景

      <?xml version="1.0" encoding="UTF-8" ?>
      <shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
      ohos:shape="rectangle">
      <corners
      ohos:radius="20"/>
      <solid
      ohos:color="#70dbdb"/>
      </shape>
  • java代码

    package com.javaaier.family.huawei.slice;
    
    import com.javaaier.family.huawei.ResourceTable;
    import com.javaaier.family.huawei.common.FinalValue;
    import ohos.aafwk.ability.AbilitySlice;
    import ohos.aafwk.content.Intent;
    import ohos.agp.components.*;
    import ohos.agp.components.webengine.*;
    import ohos.media.image.PixelMap; /**
    * @Author JavaAIer
    * @Description : webview控件例子1:用于简单的测试webview的用法 <br/>
    * 001 简单webview示例
    * @Date: 2021/4/16
    */
    public class SimpleWebViewAbilitySlice extends AbilitySlice {
    String urlAddress; ProgressBar otherWebViewProgressBar;
    TextField textWebViewUrl;
    Button buttonWebViewSurf, buttonWebViewBack, buttonWebViewRefresh, buttonWebViewForward;
    WebView webView; Component.ClickedListener clickedListener = new Component.ClickedListener() {
    @Override
    public void onClick(Component component) {
    int componentId = component.getId();
    switch (componentId) {
    case ResourceTable.Id_button_webview_surf: {
    urlAddress = textWebViewUrl.getText();
    if (urlAddress.isEmpty()) {
    return;
    }
    if (!urlAddress.startsWith(FinalValue.URL_HTTPS)) {
    urlAddress = FinalValue.URL_HTTPS + urlAddress;
    }
    webView.load(urlAddress); //允许javascript交互 WebConfig webConfig = webView.getWebConfig();
    webConfig.setDataAbilityPermit(true);
    webConfig.setJavaScriptPermit(true);
    webConfig.setLoadsImagesPermit(true);
    webConfig.setMediaAutoReplay(true);
    webConfig.setLocationPermit(true);
    webConfig.setSecurityMode(WebConfig.SECURITY_SELF_ADAPTIVE); webView.setWebAgent(new WebAgent() {
    @Override
    public void onLoadingPage(WebView webView, String url, PixelMap favicon) {
    super.onLoadingPage(webView, url, favicon);
    // 页面开始加载时自定义处理
    if (url != urlAddress) {
    textWebViewUrl.setText(url);
    } } @Override
    public void onPageLoaded(WebView webView, String url) {
    super.onPageLoaded(webView, url);
    // 页面加载结束后自定义处理
    } @Override
    public void onLoadingContent(WebView webView, String url) {
    super.onLoadingContent(webView, url);
    // 加载资源时自定义处理
    } @Override
    public void onError(WebView webView, ResourceRequest request, ResourceError error) {
    super.onError(webView, request, error);
    // 发生错误时自定义处理
    }
    });
    webView.setBrowserAgent(new BrowserAgent(SimpleWebViewAbilitySlice.this) {
    @Override
    public void onTitleUpdated(WebView webView, String title) {
    super.onTitleUpdated(webView, title);
    // 标题变更时自定义处理
    } @Override
    public void onProgressUpdated(WebView webView, int newProgress) {
    super.onProgressUpdated(webView, newProgress);
    if (newProgress < FinalValue.PROGRESS_BAR_FINISHED) {
    otherWebViewProgressBar.setVisibility(Component.VISIBLE);
    otherWebViewProgressBar.setProgressValue(newProgress);
    } else if (newProgress == FinalValue.PROGRESS_BAR_FINISHED) {
    otherWebViewProgressBar.setVisibility(Component.HIDE);
    }
    // 加载进度变更时自定义处理
    }
    });
    }
    break;
    case ResourceTable.Id_button_webview_back: {
    if (webView.getNavigator().canGoBack()) {
    webView.getNavigator().goBack();
    }
    }
    break;
    case ResourceTable.Id_button_webview_refresh: {
    webView.reload();
    }
    break;
    case ResourceTable.Id_button_webview_forward: {
    if (webView.getNavigator().canGoForward()) {
    webView.getNavigator().goForward();
    }
    }
    break;
    default: {
    System.out.println("没有选择任何的页面");
    }
    break;
    }
    }
    }; /**
    * @Author JavaAIer
    * @Description :
    * @Date: 2021/4/16 14:46
    * * @param intent
    */
    @Override public void onStart(Intent intent) {
    super.onStart(intent);
    super.setUIContent(ResourceTable.Layout_ability_simple_web_view);
    otherWebViewProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_other_webView_progressBar);
    textWebViewUrl = (TextField) findComponentById(ResourceTable.Id_text_webView_Url);
    buttonWebViewSurf = (Button) findComponentById(ResourceTable.Id_button_webview_surf);
    buttonWebViewSurf.setClickedListener(clickedListener);
    buttonWebViewBack = (Button) findComponentById(ResourceTable.Id_button_webview_back);
    buttonWebViewBack.setClickedListener(clickedListener);
    buttonWebViewRefresh = (Button) findComponentById(ResourceTable.Id_button_webview_refresh);
    buttonWebViewRefresh.setClickedListener(clickedListener);
    buttonWebViewForward = (Button) findComponentById(ResourceTable.Id_button_webview_forward);
    buttonWebViewForward.setClickedListener(clickedListener);
    webView = (WebView) findComponentById(ResourceTable.Id_webview_webview_webview); } @Override
    public void onActive() {
    super.onActive();
    } @Override
    public void onForeground(Intent intent) {
    super.onForeground(intent);
    }
    }
    /*
    * 这一截卡哇伊大喵在config.json用了,我发现用不用没啥区别啊
    * https://blog.csdn.net/qq_33259323/article/details/115596296
    * "default": {
    "network": {
    "cleartextTraffic": true,
    "securityConfig": {
    "domainSettings": {
    "cleartextPermitted": true,
    "domains": [
    {
    "subdomains": true,
    "name": "www.harmonyos.com"
    }
    ]
    }
    }
    }
    }
    *
    * */

    作者:人工智能姬

    想了解更多内容,请访问51CTO和华为合作共建的鸿蒙社区:https://harmonyos.51cto.com

001 - 使用鸿蒙WebView创建简单浏览器 step 1的更多相关文章

  1. Web Service 的创建简单编码、发布和部署

    最近,老大准备将已有的C/S架构项目中的通信部分做成通用,需要将其支持WebService为以后项目向着B/S架构升级做好铺垫,为此身为屌丝的我去各种百度WebService是个什么卵玩意,然后逐渐搭 ...

  2. 创建简单的响应式HTML5模版

    创建简单的响应式HTML5模版 HTML5目前发展势头良好,已经逐渐得到大部分浏览器不同程度的支持.许多web开发者也已经学习到了不少关于HTML 5的基础知识并开始试图使用HTML 5制作网页.与此 ...

  3. django初探-创建简单的博客系统

    django第一步 1. django安装 pip install django print(django.get_version()) 查看django版本 2. 创建项目 打开cmd,进入指定目录 ...

  4. simulink创建简单模型

    创建简单模型 您可以使用 Simulink® 对系统建模,然后仿真该系统的动态行为.Simulink 允许您创建模块图,图中的各个连接模块代表系统的各个部分,信号代表这些模块之间的输入/输出关系.Si ...

  5. 基于Gecko内核的简单浏览器实现

    分享一个基于Gecko内核的简单浏览器实现过程. 项目需要需要开发一个简单浏览器,由于被访问的网页中有大量Apng做的动画,使用IE内核的webbrowser不能播放,使用基于WebKit和Cefsh ...

  6. Intellij创建简单Springboot项目

    Intellij创建简单Springboot项目 第一步:选择创建新项目——file-new-project 第二步:选择项目类型——Spring Initializr-next 第三步:输入项目信息 ...

  7. django初探-创建简单的博客系统(一)

    django第一步 1. django安装 pip install django print(django.get_version()) 查看django版本 2. 创建项目 打开cmd,进入指定目录 ...

  8. mininet+floodlight搭建sdn环境并创建简单topo

    第一步:安装git sudo apt-get update sudo apt-get install git 测试git是否安装成功: git 第二步:安装mininet 1.获取mininet最新源 ...

  9. python创建简单网站

    前言 本方法基于web2py框架,使用web2py的完整网站数据包创建简单网站. web2py 是一个为Python语言提供的全功能Web应用框架,旨在敏捷快速的开发Web应用,具有快速.安全以及可移 ...

随机推荐

  1. 备战春招!开源社区系统 Echo 超全文档助力面试

    博主东南大学硕士在读,寒假前半个月到现在差不多一个多月,断断续续做完了这个项目,现在终于可以开源出来了,我的想法是为这个项目编写一套完整的教程,包括技术选型分析.架构分析.业务逻辑分析.核心技术点分析 ...

  2. scrapy 运行逻辑

    爬虫的步骤:发送请求获得响应→解析并提取数据→保存数据 我们沿用这个朴素的逻辑去理解scrapy 一.发送请求获得响应 1.爬虫发送请求request到引擎 2.引擎将请求request传递给调度器s ...

  3. 使用 Tye 辅助开发 k8s 应用竟如此简单(五)

    续上篇,这篇我们来进一步探索 Tye 更多的使用方法.本篇我们来了解一下如何在 Tye 中实现对分布式链路追踪. Newbe.Claptrap 是一个用于轻松应对并发问题的分布式开发框架.如果您是首次 ...

  4. idea中Maven-build lifecycle中下面标签详解

    原文链接:https://blog.csdn.net/mr_orange_klj/article/details/82153945 Maven是基于一个build lifecycle的中心概念,意味着 ...

  5. Vue学习笔记-基于CDN引入方式简单前后端分离项目学习(Vue+Element+Axios)

    一  使用环境 开发系统: windows 后端IDE: PyCharm 前端IDE: VSCode 数据库: msyql,navicat 编程语言: python3.7  (Windows x86- ...

  6. js 表格插入指定行

    js在table指定tr行上或下面添加tr行 function onAddTR(trIndex)         {             var tb = document.getElementB ...

  7. Linux安装ElasticSearch7.X & IK分词器

    前言 安装ES之前,请先检查JDK版本,es使用java编写,强依赖java环境.JDK安装过程略. 安装步骤 1.下载地址 点击这里下载7.2.0 2.解压elasticsearch-7.2.0-l ...

  8. alpine jdk 中文乱码

    一.概述 使用alpine镜像构建了一个oracle jdk的镜像,运行java业务时,查看日志,显示中文乱码. 但是,基于Alpine Linux的Docker基础镜像的镜像文件很小,也有代价: 把 ...

  9. 翻译:《实用的Python编程》04_00_Overview

    目录 | 上一节 (3 程序组织) | 下一节 (5 Python对象的内部工作原理) 4. 类和对象 到目前为止,我们的程序仅使用了内置的 Python 数据类型.本节,我们介绍类(class)和对 ...

  10. python基础学习之函数基础和部分内置函数

    在函数调用的时候,必备参数必须要传入 函数定义: def  函数名: 代码块pass return  返回值 函数名命名规则: 字母.数字和下划线组成,和变量命名规则一致 pass在这里表示什么都没有 ...