Android中WebView的一些簡單用法_Android

來源:互聯網
上載者:User

Android中WebView的一些簡單用法

一直想寫一個關於 WebView 控制項的 一些簡單運用,都沒什麼時間,這次也是擠出時間寫的,裡面的一些基礎知識就等有時間再更新講解一下,今天就先把項目出來做一些簡單介紹,過多的內容可以看我的源碼,都傳到github上了。

下面是項目的效果圖:

應用用到的是 MVP 設計模式,對這種模式還不太瞭解的可以先自行google一下,不然項目估計會看的暈,雖然My Code都很簡潔的。

對於MVP 可以帶著一個思路看源碼,那就是 activity(或其他組件)通過 xxPresenter 去拿資料,拿到資料 在 xxPresenter 再利用 xxIView(這是一個介面)更新資料,那麼activity(或其他組件)繼承 xxIView 這個介面 就可以 更新UI 了

其實 WebView 只用到一些簡單的,深入應用本篇文章會在更新!

其中:

    //設定WebView的一些縮放功能點    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);     webView.setHorizontalScrollBarEnabled(false);     webView.getSettings().setSupportZoom(true);     //設定WebView可觸摸放大縮小    webView.getSettings().setBuiltInZoomControls(true);     webView.setInitialScale(70);     webView.setHorizontalScrollbarOverlay(true);     //WebView雙擊變大,再雙擊後變小,當手動放大後,雙擊可以恢複到原始大小    //webView.getSettings().setUseWideViewPort(true);     //提高渲染的優先順序    webView.getSettings().setRenderPriority(RenderPriority.HIGH);    //允許JS執行    webView.getSettings().setJavaScriptEnabled(true);    //把圖片載入放在最後來載入渲染    //webView.getSettings().setBlockNetworkImage(true);     //用WebView將字串以HTML的形式顯示出來     //webView.loadDataWithBaseURL("fake://not/needed", <p>zzz</p>, "text/html", "utf-8", "");    //在同種解析度的情況下,螢幕密度不一樣的情況下,自動適配頁面: 

與 native 進行互動:

 mWebView.addJavascriptInterface(new WebAppInterface(customView.getContext()),"Android"); public class WebAppInterface {    Context mContext;    /** Instantiate the interface and set the context */    WebAppInterface(Context c) {      mContext = c;    }    /** Show a toast from the web page */    @JavascriptInterface    public void showToast(String toast) {      // 比如點擊 webview載入的html 片段 可以 讓應用彈出一個土司    }

這裡給 webview 設定 夜間模式:

也就往 html 頁面寫入 html 標籤 "<div class="night">"

  public static String buildHtmlWithCss(String html, String[] cssUrls, boolean isNightMode) {    StringBuilder result = new StringBuilder();    for (String cssUrl : cssUrls) {      result.append(String.format(CSS_LINK_PATTERN, cssUrl));    }    if (isNightMode) {      result.append(NIGHT_DIV_TAG_START);    }    result.append(html.replace(DIV_IMAGE_PLACE_HOLDER, DIV_IMAGE_PLACE_HOLDER_IGNORED));    if (isNightMode) {      result.append(NIGHT_DIV_TAG_END);    }    return result.toString();  }

項目還得有待改進,等這段時間忙完就跟新!!!!

項目源碼 github

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.