如何在 Android 中更改 WebView 的字型型別?


本示例說明如何在 Android 中更改 WebView 的字型型別。

步驟 1  − 在 Android Studio 中建立新專案,轉到檔案 ⇒ 新專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2  − 將以下程式碼新增到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/relativeLayout"
   android:padding="8dp"
   tools:context=".MainActivity">
   <WebView
      android:id="@+id/webView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>
</RelativeLayout>

步驟 3  – 建立 assets 資料夾。右鍵單擊 assets 資料夾 >> 建立新檔案 (webView1.html),然後新增以下程式碼:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebView9</title>
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
<style type="text/css">
   @font-face {
      font-family: 'Font';
      src:url("file:///android_asset/Font.otf")
   }
   body {
      font-family: 'Font', serif;
      font-size: medium;
      text-align: justify;
      color:#ffffff
   }
</style>
</head>
<body style="background-color:#212121">
This file was loaded from android assets folder using webView.</body>
</html>

步驟 4  − 向 src/MainActivity.java 新增以下程式碼:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
   WebView webView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      webView = findViewById(R.id.webView);
      webView.loadUrl("file:///android_asset/webView1.html");
   }
}

步驟 5  - 將以下程式碼新增到 androidManifest.xml 中:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行你的應用程式。我假設你已將實際 Android 移動裝置連線到電腦。若要從 Android Studio 執行該應用,請開啟一個專案的活動檔案,然後單擊工具欄上的執行 播放圖示 圖示。選擇你的移動裝置作為選項,然後檢視顯示預設螢幕的移動裝置 –

單擊 此處 下載專案程式碼。

更新於: 03-07-2020

1K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.