001 - 使用鴻蒙WebView建立簡單瀏覽器 step 1

  1. 打開官網,找到WebView的文檔(模擬器不支持)javascript

    鴻蒙webview的開發指南(原始連接,方便你們識別並點擊):https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158html

001 - 使用鴻蒙WebView建立簡單瀏覽器 step 1
2. 建立一個Page Ability,把基本佈局弄好java

001 - 使用鴻蒙WebView建立簡單瀏覽器 step 1

下面是代碼web

<?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. 把基本的按鈕事件弄好json

    序號 按鈕 功能
    1 跳轉 把文本框中的網址打開
    2 後退 在webview中點了新連接後,想回去看一看
    3 刷新 之前的人在網絡很差,美女圖片出不來的時候用,如今通常是發了一篇帖子後,做者會沒事點一下,看看有沒有人點贊
    4 前進 跟後退是關聯用的,就是點了新連接,回去看了看後,仍是以爲新連接更好看,就又要前進.

    代碼api

    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;
                }
            }
        };
  • 把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完了還有事?app

    從上面拷代碼的話,估計完事了.可是,我是用的回憶,可是代碼卻沒有回退,因此我仍是有必要在這兒把步驟中的問題說一說,方便不拷代碼的同窗也能跑出一個界面.主要體現以下:dom

    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" } ] } } } } * * */
     
- 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"
         }
       ]
     }
   }

做者:人工智能姬

想了解更多內容,請訪問51CTO和華爲合做共建的鴻蒙社區:https://harmonyos.51cto.com#kyzg

相關文章
相關標籤/搜索