Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách load file từ thư mục assets vào WebView Android

Giới thiệu

Ví dụ này minh họa cách tải file HTML cục bộ từ thư mục assets vào WebView bằng scheme file:///android_asset/.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Bước 3: Code MainActivity (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.webView);
        // Bật JavaScript nếu file HTML có JS
        webView.getSettings().setJavaScriptEnabled(true);
        // Load file từ assets
        webView.loadUrl("file:///android_asset/mytext.html");
    }
}

Bước 4: Tạo file HTML trong assets

  1. Chuột phải module app → New → Folder → Assets Folder → Finish.
  2. Chuột phải thư mục assets → New → File → Name: mytext.html.
<html>
<head></head>
<body>
    <h1> File HTML này được tải từ thư mục assets </h1><br/>
    <h2> Chúc bạn một ngày tốt lành! </h2>
</body>
</html>

Bước 5: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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>
                

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. WebView hiển thị nội dung file HTML từ assets.

Cách load file từ thư mục assets vào WebView Android

Giải thích & Mở rộng

Scheme file:///android_asset/

  • Đặc thù Android, chỉ dùng trong WebView.loadUrl().
  • Không thể dùng trong Intent hoặc Browser bên ngoài.
  • Đường dẫn tương đối từ thư mục assets gốc.

Tổ chức file trong assets

assets/
├── index.html
├── css/
│   └── style.css
├── js/
│   └── main.js
├── fonts/
│   └── custom.otf
└── images/
    └── logo.png

Trong HTML: <link rel="stylesheet" href="css/style.css"> (đường dẫn tương đối).

Cấu hình WebView quan trọng

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);           // Cho phép JS
settings.setDomStorageEnabled(true);           // localStorage
settings.setAllowFileAccess(true);             // Truy cập file://
settings.setAllowContentAccess(true);          // Truy cập content://
// settings.setAllowFileAccessFromFileURLs(true); // CORS cho file:// (API 16+, rủi ro bảo mật)

Xử lý Navigation trong WebView (giữ trong app)

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        if (url.startsWith("file:///android_asset/")) {
            return false; // Load trong WebView
        }
        // Link ngoài -> mở trình duyệt
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }
});

Thư mục raw vs assets

  • AssetManager.open()
  • WebView loadUrl
  • Đặc điểm assets/ res/raw/
    Truy cập Resources.openRawResource(R.raw.file)
    Cấu trúc thư mục Hỗ trợ thư mục con Phẳng (không thư mục con)
    Tên file Giữ nguyên Chỉ chữ thường, số, gạch dưới
    Nén APK Không nén (raw) Có thể nén