WebView displays HTML rich text

First, let me explain what rich text is: By definition, rich text is a cross-platform way of processing text.

Browsing through most forums and blogs, android displays rich text in two main ways:

  1. Convert Html text to SpannableString and display it through TextView.
  2. Use Webview to display Html

Html text to SpannableString

A quick mention here is that converting Html text to SpannableString is done by recognizing Html tags and then converting content to SpannableString.

The Android SDK has a way to use html.fromhtml, but it doesn’t recognize all Html tags.

If it takes too long to process Html tags, and I am not familiar with Html, so choose the second option, using Webview display

Display Html text using a Webview

github

There is no point in talking:

If you use images from the web in your HTML text, add the web request permission first

  • Core method

    webView.loadData(htmlStr, "text/html"."UTF-8");
    webView.loadDataWithBaseURL(null, htmlStr, "text/html"."UTF-8".null);
    Copy the code

    HtmlStr above is your Html text string

    Found in practical use: the webView loadData () this method shows exist in Chinese garbled, the webView. LoadDataWithBaseURL () everything is all right, it wasn’t immediately clear the reason inside. So here mainly introduce the webView. LoadDataWithBaseURL () method

    public void loadDataWithBaseURL( String baseUrl, String data, String mimeType, String encoding, String historyUrl)
    Copy the code
    • BaseUrl – The SRC address of some images in HTML text may be a relative address. Like this,

      Pictures of address in https://upload.jianshu.io/users/upload_avatars/5382223/a.jpg, if the data is/users/upload_avatars / 5382223 / a. pg then you need to https://upload.jianshu.io baseUrl assignmentCopy the code
    • Data — HTML text

    • MimeType — Text type

    • Encoding — Encoding format

    • HistoryUrl — don’t know

Learn to use

  • Simple use

    WebView webView = findViewById(R.id.web_view);
    / / set the webView
    webView.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);// Cancel the scroll bar
    webView.getSettings().setSupportZoom(false);// Scaling is not supported
    // Load HTML text
    webView.loadDataWithBaseURL(null, htmlStr, "text/html"."UTF-8".null);
    Copy the code
  • Image processing

    Of course, this simple use can not meet our needs, when the image size is too large can also slide, how can this work,

    // The dependent library
    compile 'org. Jsoup: jsoup: 1.11.2'
    Copy the code
    // Here we use jsoup to modify img attributes:
    final Document doc = Jsoup.parse(htmltext);
    
    final Elements imgs = doc.getElementsByTag("img");
    for (int i = 0; i < imgs.size(); i++) {
       	// Width fills the phone, height ADAPTS
    	imgs.get(finalI).attr("style"."width: 100%; height: auto;");
    }
    Copy the code
    // Here we use jsoup to modify the embed attributes:
    Elements embeds = doc.getElementsByTag("embed");
    for (Element element : embeds) {
        // Width fills the phone, height ADAPTS
        element.attr("width"."100%").attr("height"."auto");
    }
    
    // WebView cannot correctly identify embed as video, so change this tag to video
    doc.select("embed").tagName("video");
    Copy the code
  • Now all the pictures are as wide as the phone, and the height is self-adaptive, like some smaller pictures. If they are as wide as the screen, the picture quality is unbearable. If we are not satisfied, we need to deal with them again.

    There are two cases:

    1. The width and height attributes of the image are attached to the tag
    2. Just one SRC like me

    The processing of the two is the same, both need to know the width and height of the picture, by comparing the width of the picture with the width of the phone

    if(Width of picture > width of phone){// Width fills the phone, height ADAPTS
      	imgs.get(finalI).attr("style"."width: 100%; height: auto;");
    }else {
      	// No changes are required
    }
    Copy the code

    In the first case we can use Jsoup to get the width height of the definition

    In the second case, since there is only SRC, we need to get the width and height of the network image. Here, I used Glide to get the width and height directly. Here, the width and height need to request the network to get, so we can tell the WebView to load the Html text when the last image is processed, instead of loading it directly.

    // The dependent library
    compile 'com. Making. Bumptech. Glide: glide: 3.8.0'
    Copy the code
    Glide.with(this)
       	.load(src)
       	.asBitmap()
       	.skipMemoryCache(true)
       	.diskCacheStrategy(DiskCacheStrategy.NONE)
       	.into(new SimpleTarget<Bitmap>() {
       		@Override
       		public void onResourceReady(
              Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
            	int width = bitmap.getWidth();
                intheight = bitmap.getHeight(); }});Copy the code
  • After processing with Jsoup, instead of loading the original htmlStr, you load jsoup’s Document

    webView.loadDataWithBaseURL(null, doc.toString(), "text/html"."UTF-8".null);
    Copy the code