1.創建一個專案
一路默認就可以

2.
右鍵點擊app創建一個和res同級的assets 檔案夾,在此檔案夾下把html檔案以及所要渲染的靜態檔案放進去


如這是我的檔案夾
注:在html中參考css,js等靜態檔案方法和通常一樣,修改一下路徑就可以
file:///android_asset/js/jquery.min.js"
3.創建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">
<!-- <TextView-->
<!-- android:layout_width="wrap_content"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:text="Hello World!"-->
<!-- app:layout_constraintBottom_toBottomOf="parent"-->
<!-- app:layout_constraintLeft_toLeftOf="parent"-->
<!-- app:layout_constraintRight_toRightOf="parent"-->
<!-- app:layout_constraintTop_toTopOf="parent" />-->
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mWebView">
</WebView>
</androidx.constraintlayout.widget.ConstraintLayout>
修改MainActiviy.java檔案,完整代碼如下:
package com.example.webviewdome;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 實體化
mWebView = (WebView) findViewById(R.id.mWebView);
// 開啟javascript 渲染
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
// 載入內容
mWebView.loadUrl("file:///android_asset/index.html");
// 測驗遠程的 mWebView.loadUrl("http://www.itxdl.cn");
}
}
然后就可以運行啦

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/287397.html
標籤:其他
