如何在 Android WebView 中載入 html 內容?
本例演示如何在安卓 WebView 中載入 HTML 內容。
步驟 1 − 在 Android Studio 中新建一個專案,轉到 File ⇒ New Project 並填寫所有必需資訊建立新專案。
步驟 2 − 在 res/layout/activity_main.xml 中新增以下程式碼。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>在以上程式碼中,我們已獲取 WebView 來顯示 HTML 內容。
步驟 3 − 在 src/MainActivity.java 中新增以下程式碼
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setLightTouchEnabled(true);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setGeolocationEnabled(true);
web_view.setSoundEffectsEnabled(true);
web_view.loadData("<html><body>Hello, world!</body></html>",
"text/html", "UTF-8");
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}執行你的程式。我假定你的真機已連線到電腦。要從 Android Studio 執行程式,開啟專案中某個 activity 檔案,然後單擊工具欄上的執行
圖示。選擇你的移動裝置為執行選項,然後檢視你的移動裝置上顯示的預設介面 -

單擊 此處 下載專案程式碼
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP