Android-記錄怎么用webView加載含有base64格式圖片的html片段

最近遇到個(gè)問(wèn)題Android里面用webView加載含有base64格式圖片的html,很多人可能可以直接加在使用下面這種方法,但是運(yùn)行之后你會(huì)發(fā)現(xiàn)里面的base64格式圖片顯示不出來(lái)。

 webview.loadData(Html.fromHtml(content).toString(), "text/html", "UTF-8");

看網(wǎng)上的說(shuō)有的方法是把里面的base64格式的圖片先轉(zhuǎn)換成圖片然后再存到服務(wù)器,然后再把base64替換下,這樣雖然也可以實(shí)現(xiàn)但是我感覺(jué)很麻煩,并且我們的需求就是Android處理,服務(wù)器不改了,這是我看到的那個(gè)替換的方法有需要的可以看下(https://blog.csdn.net/shirley153/article/details/96978104)。
話不多說(shuō)了,下面是我想到的方法以及實(shí)現(xiàn),我的方法就是
1.創(chuàng)建一個(gè)web.html文件,并且創(chuàng)建一個(gè)有參數(shù)的方法供Android調(diào)用,就是很簡(jiǎn)單的那種

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <style>
            html {
                padding: 15px;
            }
            body {
                word-wrap: break-word;
                font-size: 13px;
                padding: 0px;
                margin: 0px
            }
            p {
                padding: 0px;
                margin: 0px;
                font-size: 16px;
                color: #222222;
                line-height: 1.3;
            }
            img {
                padding: 0px, margin:0px;
                max-width: 100%;
                width: auto;
                height: auto;
            }
        </style>
</head>
<body>
<div id="content" style="width: 100%;height: 100%;">111</div>
</body>
<script charset="UTF-8">
        function showWebView(param){
            document.getElementById("content").innerHTML=param.content;
        }
    </script>
</html>

2.通過(guò)Android里面的webView調(diào)用html里面的有參方法,去加載。下面是Activity和布局
MainActivity

package com.qy.ndkdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.sample_text);
        WebSettings websettings = webView.getSettings();
        webView.loadUrl("file:///android_asset/web.html"); //得到web.html文件路徑,并且加載
        websettings.setJavaScriptEnabled(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setJavaScriptEnabled(true);
      //這里要注意調(diào)用js的方法一定要再頁(yè)面加載完成后(onPageFinished里面)調(diào)用,不然會(huì)不成功
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
              //webjson.json,真實(shí)項(xiàng)目中一般都是網(wǎng)絡(luò)獲取,現(xiàn)在就直接寫在本地了
                String jsonStr = getJson(MainActivity.this, "webjson.json");//獲取assets目錄下的json文件數(shù)據(jù)
                String str = "javascript:showWebView(" + jsonStr + ")"; //調(diào)用js方法
                webView.loadUrl(str);
            }
        });

    }

    //將json數(shù)據(jù)轉(zhuǎn)換成字符串
    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}

MainActivity 的布局文件,很簡(jiǎn)單就一個(gè)webView

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <WebView
        android:id="@+id/sample_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

用到的webjson.json

{
  "content": "<ul><li>這是簡(jiǎn)單的測(cè)試<img src=\"data:image/jpeg;base64,base64格式編碼,自己替換吧,不然文章太長(zhǎng)了\"></li></ul>"
}
web.html和webjson.json的存放目錄

運(yùn)行結(jié)果截圖:



到這里就Ok了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容