目录
首先在界面文件中使用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/apk/res/android"
xmlns:app="http://schemas.android/apk/res-auto"
xmlns:tools="http://schemas.android/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/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代码,希望可以帮助到有需要的人,喜欢的可以点赞收藏噢~
更多推荐
使用WebView加载HTML代码
发布评论