问题
最近公司需求需要用webView显示html代码,而不是用loadUrl加载网址,我想起来之前我解决过这个问题,但是却没有记录,如今特意记录一下。

WebView提供了loadDataloadDataWithBaseURL这两个方法,该方法用于加载并显示HTML代码。

效果如下:(点击蓝色超链接可以跳转)
在这里插入图片描述
在这里插入图片描述

首先在activity_main.xml使用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/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity文件中进行调用加载HTML代码

第一种方法

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.web_view);

        String sss = "<html><head><title>欢迎</title></head><body><h2>欢迎您访问"+
                "<a href="https://blog.csdn.net/houruoyu3">houruoyu3的博客</a></h2></body></html>";

        webView.loadData(sss,"text/html","utf-8");

    }
}

通过这个操作可以实现在WebView中加载HTML代码

除了第一种方法外,还有第二种方法

webView.loadDataWithBaseURL(null, sss, "text/html", "utf-8", null);

使用loadDataWithBaseURL加载HTML代码,个人建议使用第二种方法,第一种方法部分模拟器上会出现中文乱码现象,希望这篇文章能够帮到大家,喜欢的可以点赞收藏,谢谢。

原文地址:https://blog.csdn.net/houruoyu3/article/details/125766505

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_21420.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注