欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webView加载html两种方式

程序员文章站 2022-04-03 08:38:48
...

加载main/assets目录下的html文件

  • html文件的位置

![YJ7[email protected]@29SGXIEA%$C9Z6.png

  • html代码
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="http://www.google.com" id="cse-search-box">
  <div>
    <p>google search</p>
    <input type="text" name="q" size="20" />
    <input type="submit" name="sa" value="Search" />
  </div>
</form>
</body>
</html>
  • java代码
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.loadUrl("file:///android_asset/bxd-note.html");
  }

加载html格式的字符串

  • 首先要处理一下原生的html代码
 String html_str="<!DOCTYPE html>"
                + "<html lang='en'>"
                + "<head>"
                + "</head>"
                + "<body>"
                + "<form action='http://www.google.com'  id='cse-search-box'>"
                + "<div>"
                + "<p>google search</p>"
                + "<input type='text' name='q' size='20' />"
                + "<input type='submit' name='sa' value='Search' />"
                + "</div>"
                + "</form>"
                + "</body>"
                + "</html>";
  • java代码部分
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webView);
        String html_str="<!DOCTYPE html>"
                + "<html lang='en'>"
                + "<head>"
                + "</head>"
                + "<body>"
                + "<form action='http://www.google.com'  id='cse-search-box'>"
                + "<div>"
                + "<p>google search</p>"
                + "<input type='text' name='q' size='20' />"
                + "<input type='submit' name='sa' value='Search' />"
                + "</div>"
                + "</form>"
                + "</body>"
                + "</html>";

        mWebView.loadDataWithBaseURL(null, html_str, "text/html", "utf-8", null);
    }