Android WebView UTF-8 not showing

后端 未结 2 1547
名媛妹妹
名媛妹妹 2020-12-01 05:30

I have a webview and am trying to load simple UTF-8 text into it.

mWebView.loadData(\"將賦予他們的傳教工作標示為\", \"text/html\", \"UTF-8\");

But the W

相关标签:
2条回答
  • 2020-12-01 05:56

    This problem goes back to at least Gingerbread

    This seems to have been broken in some form or fashion forever. Issue 1733

    Use loadDataWithBaseURL instead of loadData

    // Pretend this is an html document with those three characters
    String scandinavianCharacters = "øæå";
    
    // Won't render correctly
    webView.loadData(scandinavianCharacters, "text/html", "UTF-8");
    
    // Will render correctly
    webView.loadDataWithBaseURL(null, scandinavianCharacters, "text/html", "UTF-8", null);
    

    Now the part that is truly annoying is that on the Samsung Galaxy S II (4.0.3) loadData() works just fine, but testing on the Galaxy Nexus (4.0.2) the multi-byte characters are garbled unless you use loadDataWithBaseURL(). WebView Documentation

    Recent versions of Android

    Some are reporting a change in the behavior of the loadData calls requiring the mimeType to include charset=utf-8.

    webView.loadData(scandinavianCharacters, "text/html; charset=utf-8", "UTF-8");
    

    Discussion

    The first time I saw this my boss brought me his phone, an early Nexus, while I was developing at the time on a Samsung Galaxy II and it showed up in our economic news feed on his phone which had a lot of non-ASCII characters. So, not only is this a long standing issue within Android, but it also isn't consistent between device makers. This is a matter where you have to program defensively.

    0 讨论(0)
  • 2020-12-01 05:57

    Use:

    mWebView.loadDataWithBaseURL(null, "將賦予他們的傳教工作標示為", "text/html", "utf-8", null);
    

    or using WebSettings with setDefaultTextEncoding:

    WebSettings settings = mWebView.getSettings();
    settings.setDefaultTextEncodingName("utf-8");
    

    For recent versions of Android, API 16 to 22 it was tested and work properly using loadData() method, requires the mimeType to include: "charset=utf-8".

    WebView mWebView = (WebView) findViewById(R.id.myWebView);
    WebSettings settings = mWebView.getSettings();
    settings.setDefaultTextEncodingName("utf-8");                   
    mWebView.loadData(myCharacters, "text/html; charset=utf-8",null);
    

    or

      mWebView.loadData(myCharacters, "text/html; charset=utf-8","UTF-8");
    
    0 讨论(0)
提交回复
热议问题