使用WebView加载HTML代码

目录

首先在界面文件中使用WebView控件(activity_main.xml)

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


前言:

        WebView提供了一个loadData(String data,String mimeType,String encoding)方法,该方法可用于加载并显示HTML代码,同时,Android9已经解决了当它加载包含中文的HTML内容时将会显示乱码。

效果截图:(点击蓝色部分即可实现跳转)

  • 首先在界面文件中使用WebView控件(activity_main.xml)

<?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/show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="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.show);

        StringBuilder sb = new StringBuilder();
        sb.append("<html>");
        sb.append("<head>");
        sb.append("<title>欢迎您</title>");
        sb.append("</head>");
        sb.append("<body>");
        sb.append("<h2>欢迎您访问<a href=\"https://blog.csdn.net/qq_50272406?spm=1000.2115.3001.5343\">"+"安卓小白~的博客</a></h2>");
        sb.append("</body>");
        sb.append("</html>");
        webView.loadData(sb.toString(),"text/html","utf-8");
    }
}

       通过以上的操作,可以实现简单的WebView中加载HTML代码,希望可以帮助到有需要的人,喜欢的可以点赞收藏噢~

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值